Python基础— 文件读写模式

Python基础— 文件读写模式

Python2.7 文件读写模式简单介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# coding=utf8


# python 不换行2.x 句尾加, 3.x 添加end=''
def funcFileMode(mode='r',file='G:/test1.txt'):
'''
# r 只读 如果文件不存在则报错
mode = 'r'
with open(file,mode) as wo:
for line in wo:
print (line.strip())
'''
'''
# r+ 可读可写 ,若文件不存在,即报错,写入时采用添加
mode = 'r+'
with open(file,mode) as wo1:
for line in wo1:
print (line.strip())
wo1.write("new world ")
'''
'''
# w 可写,若文件不存在,即报错,写入时采用覆盖
mode = 'w'

with open(file,mode) as wo2:
wo2.write("new world ")
'''
'''
# w+ 可写不可读,若文件不存在,即创建,写入时采用覆盖
mode = 'w+'
with open(file,mode) as wo3:
wo3.write("new world ")

'''
'''
# a 可写不可读,若文件不存在,即创建,写入时采用追加
mode = 'a'
with open(file,mode) as wo4:
wo4.write("new world ")

'''
# a+ 可写可读,若文件不存在,即创建,写入时采用追加
mode = 'a+'
with open(file,mode) as wo5:
wo5.write("new world ")
# 设置文件指针指向文件首
wo5.seek(0)
print wo5.read()



if __name__ == '__main__' :


funcFileMode()

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×