简单总结下文件读写的常用方法:
path = ‘XXX'
destPath = ‘XXX'
打开文件
open后面一个参数:r 读;rb以二进制方式读;w 写;wb以二进制方式写
f = open(path, 'r')
读文件
print f.read()
记得关闭
f.close()
还可以写成
try:
f = open(path, 'r')
print(f.read())
finally:
if f:
f.close()
更简洁,并且不用调close,引用了with语句自动帮我们调用了close()方法
with open(path, 'r') as f:
print f.read()
文件过大,建议一行行地读,当然此方式仅适用于以字符的方式读取
with open(path, 'r') as f:
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉
读取二进制文件
f = open(path, 'rb')
print f.read()
写文件
w :覆盖写,wb:覆盖写二进制,a:追加写
f = open('/Users/hongtao/work/tes', 'c')
f.write('123')
f.close()
with open('/Users/hongtao/work/tes', 'a') as f:
f.write('Hello, world!')
copy文件
rf = open(path,'r')
wf = open(destPath,'a')
wf.write(rf.read())
rf.close()
wf.close()
另外附几张表: