我已经编写了一个简单的方法将字典写入CSV文件。它可以正常工作,但我想知道在速度方面是否可以改进(在我的测试中,写入1000行CSV需要6秒钟)。
我的问题是:如何改善这段代码的速度?(如果可能的话)
非常感谢您的帮助。
我的问题是:如何改善这段代码的速度?(如果可能的话)
非常感谢您的帮助。
def fast_writer(self, f_name, text_dict):
try:
start = timer()
# Windows
if os.name == "nt":
with open(f_name, 'w', newline='') as self._csv_file:
self._writer = csv.writer(self._csv_file)
for self._key, self._value in text_dict.items():
self._writer.writerow([self._key, self._value])
# Unix/Linux
else:
with open(f_name, 'w') as self._csv_file:
self._writer = csv.writer(self._csv_file)
for self._key, self._value in text_dict.items():
self._writer.writerow([self._key, self._value])
end = timer()
print("[FastWriter_time] ", end - start)
except BaseException:
print("[ERROR] Unable to write file on disk. Exit...")
sys.exit()