Python、Dict 到 CSV:有没有更快的方法?

Ser*_*osa 3 python csv performance python-3.x

我写了一个简单的方法来将字典写入 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()
Run Code Online (Sandbox Code Playgroud)

sac*_*cuL 5

如果您真的只是在寻找一种更快的方法来执行此操作,pandas那么内置了此类方法,并且经过了很好的优化!以下面的代码为例:

import numpy as np
import pandas as pd

# This is just to generate a dictionary with 1000 values:
data_dict = {'value':[i for i in np.random.randn(1000)]}

# This is to translate dict to dataframe, and then same it
df = pd.DataFrame(data_dict)
df.to_csv('test.csv')
Run Code Online (Sandbox Code Playgroud)

在我的机器上将字典写入数据帧并将数据帧写入 csv大约需要 0.008 秒