打开文件的几种模式
open('path') #默认只读打开
open('path','r+') #读写模式打开。如果有内容,就会从头覆盖相应字符串的内容
open('path','w')#写入,覆盖文件,重新写入。没有文件就自己创建
open('path','w+ ')#读写,作用同上
open('path','a')# 写入,在文件末尾追加内容,文件不存在就创建
open('path','a'+)#读写,同上。 最常用
open('path','b') #打开二进制文件
open('path','U')#支持所有的换行符号
例子:用户注册
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/usr/bin/env python
#coding:utf-8
f
=
open
(
'user.txt'
,
'a+'
)
#单行写入
#f.write("wd:1234")
#多行写入
#names=["pc:123\n","panda:123\n"]
#f.writelines(names)
#交互式注册
while
True
:
name
=
raw_input
(
'请输入用户姓名:'
).strip()
password
=
raw_input
(
'请输入您的密码:'
).strip()
repass
=
raw_input
(
'请再次输入密码:'
).strip()
if
len
(name)
=
=
0
:
print
"用户名不能为空,请重新输入!!"
continue
;
if
len
(password)
=
=
0
or
password !
=
repass:
print
"密码输入有误"
continue
;
else
:
print
"恭喜你,注册成功"
break
;
f.write(
"%s:%s"
%
(name,password))
f.close()
|
本文转自 shouhou2581314 51CTO博客,原文链接:http://blog.51cto.com/thedream/1830614,如需转载请自行联系原作者