文件读写
写入测试文件:
%%writefile test.txt
this is a test file.
hello world!
python is good!
today is a good day.
读文件
使用 open 函数来读文件,使用文件名的字符串作为输入参数:
f = open('test.txt')
默认以读的方式打开文件,如果文件不存在会报错。
可以使用 read 方法来读入文件中的所有内容:
text = f.read()
print (text)
也可以按照行读入内容,readlines 方法返回一个列表,每个元素代表文件中每一行的内容:
f = open('test.txt')
lines = f.readlines()
print (lines)
使用完文件之后,需要将文件关闭。
f.close()
事实上,我们可以将 f 放在一个循环中,得到它每一行的内容:
f = open('test.txt')
for line in f:
print (line)
f.close()
删除刚才创建的文件:
import os
os.remove('test.txt')
写文件
我们使用 open 函数的写入模式来写文件:
f = open('myfile.txt', 'w')
f.write('hello world!')
f.close()
使用 w 模式时,如果文件不存在会被创建,我们可以查看是否真的写入成功:
print (open('myfile.txt').read())
如果文件已经存在, w 模式会覆盖之前写的所有内容:
f = open('myfile.txt', 'w')
f.write('another hello world!')
f.close()
print (open('myfile.txt').read())
除了写入模式,还有追加模式 a ,追加模式不会覆盖之前已经写入的内容,而是在之后继续写入:
f = open('myfile.txt', 'a')
f.write('... and more')
f.close()
print (open('myfile.txt').read())
写入结束之后一定要将文件关闭,否则可能出现内容没有完全写入文件中的情况。
还可以使用读写模式 w+:
f = open('myfile.txt', 'w+')
f.write('hello world!')
f.seek(6)
print (f.read())
f.close()
这里 f.seek(6) 移动到文件的第6个字符处,然后 f.read() 读出剩下的内容。
import os
os.remove('myfile.txt')
二进制文件
二进制读写模式 b:
import os
f = open('binary.bin', 'wb')
f.write(os.urandom(16))
f.close()
f = open('binary.bin', 'rb')
print (repr(f.read()))
f.close()
import os
os.remove('binary.bin')
换行符
不同操作系统的换行符可能不同:
\r\n\r\n
使用 U 选项,可以将这三个统一看成 \n 换行符。
关闭文件
在Python中,如果一个打开的文件不再被其他变量引用时,它会自动关闭这个文件。
所以正常情况下,如果一个文件正常被关闭了,忘记调用文件的 close 方法不会有什么问题。
关闭文件可以保证内容已经被写入文件,而不关闭可能会出现意想不到的结果:
f = open('newfile.txt','w')
f.write('hello world')
g = open('newfile.txt', 'r')
print (repr(g.read()))
虽然这里写了内容,但是在关闭之前,这个内容并没有被写入磁盘。
使用循环写入的内容也并不完整:
f = open('newfile.txt','w')
for i in range(3000):
f.write('hello world: ' + str(i) + '\n')
g = open('newfile.txt', 'r')
print (g.read())
f.close()
g.close()
import os
os.remove('newfile.txt')
出现异常时候的读写:
f = open('newfile.txt','w')
for i in range(3000):
x = 1.0 / (i - 1000)
f.write('hello world: ' + str(i) + '\n')
查看已有内容:
g = open('newfile.txt', 'r')
print (g.read())
f.close()
g.close()
可以看到,出现异常的时候,磁盘的写入并没有完成,为此我们可以使用 try/except/finally 块来关闭文件,这里 finally 确保关闭文件,所有的写入已经完成。
f = open('newfile.txt','w')
try:
for i in range(3000):
x = 1.0 / (i - 1000)
f.write('hello world: ' + str(i) + '\n')
except Exception:
print "something bad happened"
finally:
f.close()
g = open('newfile.txt', 'r')
print g.read()
g.close()
with 方法
事实上,Python提供了更安全的方法,当 with 块的内容结束后,Python会自动调用它的close 方法,确保读写的安全:
with open('newfile.txt','w') as f:
for i in range(3000):
x = 1.0 / (i - 1000)
f.write('hello world: ' + str(i) + '\n')
与 try/exception/finally 效果相同,但更简单。
g = open('newfile.txt', 'r')
print g.read()
g.close()
所以,写文件时候要确保文件被正确关闭。
import os
os.remove('newfile.txt')