python学习笔记15-文件读写
读文件
f = open(r'F:\\test.txt') #等价于f = open(r'F:\\test.txt','r') 'r'模式为默认值
x = f.read()
f.close()
x
'this is a test1\nthis is a test2\n'
逐行读
f = open(r'F:\\test.txt')
for line in f:
print(line,end='')
this is a test1
this is a test2
读完文件后需要用f.close() 来关闭文件并释放系统资源,with写法可防止句体结束后文件没有被关闭
with open(r'F:\\test.txt') as f:
for line in f:
print(line,end='')
this is a test1
this is a test2
f.closed
True
写文件
f = open(r'F:\\test.txt','w')
f.write('this is a test3\n')
f.close()
f = open(r'F:\\test.txt')
x = f.read()
f.close()
x
'this is a test3\n'
'w'模式下原文件内容被覆盖
f = open(r'F:\\test.txt','a')
f.write('this is a test4')
f.close()
f = open(r'F:\\test.txt')
x = f.read()
f.close()
x
'this is a test3\nthis is a test4'
'a'模式下原文件内容保留,新写入的内容追加在原文件内容末尾