4. 测试
测试文件test.txt,内容如下:
Hello,Python www.jb51.net This is a test file
用一小段代码来测试写入文件直观的显示它们的不同
test = [ "test1n", "test2n", "test3n" ]
f = open("test.txt", "a+")
try:
#f.seek(0)
for l in test:
f.write(l)
finally:
f.close()
a+、w+和r+模式的区别(测试后还原test.txt)
a+模式
# cat test.txt Hello, Python www.jb51.net This is a test file test1 test2 test3
w+模式
# cat test.txt test1 test2 test3
r+模式
在写入文件前,我们在上面那段代码中加上一句f.seek(0),用来定位写入文件写入位置(文件开头),直接覆盖字符数(注意n也是一个字符)
# cat test.txt test1 test2 test3 inuxeye.com This is a test file
注意:r+模式打开文件时,此文件必须存在,否则就会报错,‘r'模式也如此
其他测试
>>> f = open('test.txt')
>>> f.read() #读取整个文件,字符串显示
'Hello,Pythonnwww.jb51.netnThis is a test filen'
>>> f.read() #指针在文件末尾,不能再读取内容
''
>>> f = open('test.txt')
>>> f.readline() #一次读一行,指针在该行末尾
'Hello,Pythonn'
>>> f.tell() #改行的字符长度
13
>>> f.readline()
'www.jb51.netn'
>>> f.tell()
30
>>> f.readline()
'This is a test filen'
>>> f.tell()
50
>>> f.readline()
''
>>> f.tell() #指针停在最后一行
50
>>> f = open('test.txt')
>>> f.readlines() #读取整个文件,以列表显示
['Hello,Pythonn', 'www.jb51.netn', 'This is a test filen']
>>> f.tell() #指针在最后一行
50
>>> f = open('test.txt','w') #覆盖创建新文件
>>> f.write('Hello,Python!') #如果写入内容小于1024,会存在内存,否则需要刷新
>>> f.flush() #写入到硬盘
>>> f.close() #关闭文件会自动刷新
>>> f.write('Hello,Linuxeye') #关闭后,写失败,提示文件已经关闭
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file










