关于python文件写入问题
第一种、用for循环不断打开文件写入关闭 测试代码数据如下:
import time begin = time.perf_counter() def a(f, lis): f.write(lis + '\n') lis = 'hello' lis2 = 'hello2' for i in range(100): with open('ces.txt', 'a+')as f: # 写入文件 a(f, lis) for j in range(10): with open('ces.txt', 'a+')as b: # 写入文件 a(b, lis2) b.close() f.close() end = time.perf_counter() print('处理时长:' + '%.2f' % (end - begin) + '秒') # 处理时长:7.27秒
第二种、下面是打开文件再for循环关闭的测试
import time begin = time.perf_counter() def a(f, lis): f.write(lis + '\n') lis = 'hello' lis2 = 'hello2' with open('ces.txt', 'a+')as f: # 写入文件 for i in range(100): a(f, lis) with open('ces.txt', 'a+')as b: # 写入文件 for j in range(10): a(b, lis2) b.close() f.close() end = time.perf_counter() print('处理时长:' + '%.2f' % (end - begin) + '秒') # 处理时长:0.73秒
总结如下:
1.两者所花的时间差约10倍之长,推荐使用第二种
2.文件内容写入顺序是从下到上