文件的操作:
打开文件的方式:
>>> open('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>
>>> file('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x2b00cac7e780>
>>> f = open ('test.txt', 'w')
>>> print f
<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>
注: w -> 写操作 r->读操作 a-> 文本末尾添加 r+ ->可读可写 b->二进制读写 需要和w r 配合使用 比如:rb wb
读文件操作 :
1. 默认读完
>>> f = open('test1.txt', 'r')
>>> f.read()
2. 逐行读取文件
>>> f = open('test1.txt', 'r')
>>> f.readline()
>>> f=open('test1.txt', 'r')
>>> f.readline()
'This is the first line in the file.\n'
>>> f.readline()
'this is the second line in the file.\n'
>>> f.readline()
'this is the third line in the file.\n'
>>> f.readline()
'this is the 4th line in the file.\n'
>>> f.readline()
'this is the 5th line in the file.\n'
>>> f.readline()
'this is the 6th line in the file.\n'
>>> f.readline()
'this is the 7th line in the file.\n'
>>> f.readline()
'this is the 8th line in the file.\n'
>>> f.readline()
'this is the 9th line in the file.\n'
>>> f.readline()
'this is the 10th line in the file.\n'
>>> f.readline()
'\n'
>>> f.readline()
''
3. 读全文,系统自动以‘\n’结尾表示换行,并且每行作为list成员,以逗号分隔!
>>> f = open('test1.txt', 'r')
>>> f.readlines()
>>> f=open('test1.txt', 'r')
>>> f.readlines()
['This is the first line in the file.\n', 'this is the second line in the file.\n', 'this is the third line in the file.\n', 'this is the 4th line in the file.\n', 'this is the 5th line in the file.\n', 'this is the 6th line in the file.\n', 'this is the 7th line in the file.\n', 'this is the 8th line in the file.\n', 'this is the 9th line in the file.\n', 'this is the 10th line in the file.\n', '\n']
for 循环读取文件:
>>> f=open('test1.txt', 'r')
>>> for line in f:
... print line
...
This is the first line in the file.
this is the second line in the file.
this is the third line in the file.
this is the 4th line in the file.
this is the 5th line in the file.
this is the 6th line in the file.
this is the 7th line in the file.
this is the 8th line in the file.
this is the 9th line in the file.
this is the 10th line in the file.
以读写方式打开文件,查找偏移量对应的值并读出。
>>> f=open('test2.txt', 'r+')
>>> f.write('0123456789\n')
>>> f.seek(5)
>>> f.read(1)
'5'
>>> f.seek(-3, 2)
>>> f.read(1)
'8'