您的位置:首页 > 编程语言 > Python开发

python文件操作

2016-04-13 21:13 423 查看
1.打开文件的模式r : 只读模式打开文件w : 以写模式打开文件,如果该文件存在内容,会直接覆盖a : 以追加的模式打开文件w+:以写读模式打开文件,如果该文件存在内容,会直接覆盖r+:可读写文件rU:可以将\r \n 自动转换成\nrb wb ab:已二进制的方式处理文件2.写操作
>>> 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.读操作
>>> 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.追加操作
>>> f = open("/tmp/test.log","a")
>>> f.write('append')
>>> f.close()

$ more test.log
1th
2th
3th
append
5.打开文件
with open('/tmp_guoxianqi/test.txt','r') as f:
print(f.readline().strip())
6.close7.fileno8.flush9.read
1)读取3个字符
>>> f.close()
>>> f = open('test.log','r')
>>> f.read(3)
'asd'
>>> f.close()
10.readable:是否可读11.readline:读取一行
>>> f = open('test.log','w')
>>> f.write("1.sdasddsad\n")
12
>>> f.write("2.sdasddsad\n")
12
>>> f.write("3.sdasddsad\n")
12
>>> f.close()
>>> f = open('test.log','r')
>>> f.readline()
'1.sdasddsad\n'
>>> f.readline()
'2.sdasddsad\n'
>>> f.readline()
'3.sdasddsad\n'
12.seek:指定文件中的指针位置
>>> f = open('test.log','w')
>>> f.write('asdasda')
7
>>> f.close()
>>> f = open('test.log','r')
>>> f.seek(3)
3
>>> f.read()
'asda'
>>> f.close()
13.tell查看指针位置
>>> f = open('test.log','w')
>>> f.write('asdasda')
7
>>> f.close()
>>> f = open('test.log','r')
>>> f.tell()
0
>>> f.read(2)
'as'
>>> f.tell()
2
>>> f.close()
14.truncate:删除指针位置之后的数据
15.writeable16.write
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 文件操作