Python 添加一个空白/空列。文件

chr*_*yer 5 python csv

您好,我有一个数据库,我正在尝试从中快速制作 .csv 文件。

我的数据看起来像这样。

Song_Name,File_Name,Artist_Name,Artist_ID
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Song1,filename1,artistname,artist001
Run Code Online (Sandbox Code Playgroud)

这就是我需要它的外观。

Song_Name,,File_Name,Artist_Name,,Artist_ID
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Run Code Online (Sandbox Code Playgroud)

什么是最好的方法来做到这一点。谢谢你。

eri*_*mjl -2

这是我的回答,希望对您有所帮助。

首先,我建议在 IPython 环境中使用 Pandas,而不是 Python 的内置 CSV 阅读器。Pandas 提供了一些强大的工具来处理表格数据。也就是说,您可以使用 Python 的内置 CSV 模块执行以下操作。

with open('data.csv', 'r') as infile:
    with open('data_out.csv', 'w') as outfile:
        for line in csv.reader(infile):
            newline = []
            for element in line:
                if line.index(element) in [1, 3]: # crucial part here: identify where you want to make insertions
                    newline.append(' ')
                newline.append(element)
            print(newline)
            csv.writer(outfile).writerow(newline)
Run Code Online (Sandbox Code Playgroud)

作为是否使用 Pandas 与简单地迭代文件之间的评估,这取决于 - 根据我自己的经验,我发现通过将大型 CSV 文件加载到 Pandas 中会产生相当大的内存开销,因此我转而使用 Python 处理我的数据文件而是内置模块。也就是说,我可能还没有足够深入地掌握 Pandas。:-)