提高编写文件的性能-Python 3.4
我对Python不太熟悉,根据我的知识和一些浏览,我编写了下面提到的脚本,该脚本基本上查找C:\temp\dats文件夹中的所有文件,并将其写入C:\temp\datsOutput\output.text文件,由于某些原因,我的代码运行速度非常慢,有谁能建议我改进它以获得更好的性能提高编写文件的性能-Python 3.4,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我对Python不太熟悉,根据我的知识和一些浏览,我编写了下面提到的脚本,该脚本基本上查找C:\temp\dats文件夹中的所有文件,并将其写入C:\temp\datsOutput\output.text文件,由于某些原因,我的代码运行速度非常慢,有谁能建议我改进它以获得更好的性能 import os a = open(r"C:\temp\datsOutput\output.txt", "w") path = r'C:\temp\dats' for filenam
import os
a = open(r"C:\temp\datsOutput\output.txt", "w")
path = r'C:\temp\dats'
for filename in os.listdir(path):
fullPath = path+"\\"+filename
with open(fullPath, "r") as ins:
for line in ins:
a.write(line)
两次加速。首先,立即复制整个文件。其次,将文件视为二进制文件(打开文件时,在“r”或“w”之后添加一个“b”) 加起来,运行速度大约快10倍 最终代码如下所示
import os
a = open(r"C:\temp\datsOutput\output.txt", "wb")
path = r'C:\temp\dats'
for filename in os.listdir(path):
fullPath = path+"\\"+filename
with open(fullPath, "rb") as ins:
a.write(ins.read())