kuuty 发表于 2016-4-14 09:19:03

python文件操作

1.打开文件的模式

[*]r : 只读模式打开文件

[*]w : 以写模式打开文件,如果该文件存在内容,会直接覆盖

[*]a : 以追加的模式打开文件

[*]w+:以写读模式打开文件,如果该文件存在内容,会直接覆盖


2.写操作

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> f = open("/tmp/test.log","w")
>>> f.write("1th\n")
4
>>> f.write("2th\n")
4
>>> f.write("3th\n")
4
>>> f.close()

$ more test.log
1th
2th
3th





3.读操作

1
2
3
4
5
6
7
8
9
>>> f = open("/tmp/test.log","r")
>>> f.read()
'1th\n2th\n3th\n'    #所有内容读取
>>> f.close()

>>> f = open("/tmp_guoxianqi/test.log","r")
>>> f.readlines()
['1th\n', '2th\n', '3th\n']    #一行一行读取,成列表格式
>>> f.close()





4.追加操作

1
2
3
4
5
6
7
8
9
>>> f = open("/tmp/test.log","a")
>>> f.write('append')
>>> f.close()

$ more test.log
1th
2th
3th
append






页: [1]
查看完整版本: python文件操作