Python添加空白/空列。 CSV

时间:2014-10-29 02:00:26

标签: 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

这就是我需要它的样子。

Song_Name,,File_Name,Artist_Name,,Artist_ID
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001
Song1,,filename1,artistname,,artist001

这是最好的方法。谢谢。

4 个答案:

答案 0 :(得分:1)

您只需写入 None 或空字符串 '',即可在 csv 中插入空白“列”。

例如:

with open('songs.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(
        ['Song_Name', None, 'File_Name', 'Artist_Name', None, 'Artist_ID']
    )  # Write headers
    # Now you iterate over your data:
    for row in data:
        writer.writerow([row['song_name'], None, row['file_name'], ...])

您的 csv 文件将正确显示空白列所需的额外逗号,如果需要,包括尾随逗号。

如果您使用 DictWriter,那就更简单了:

with open('songs.csv', 'w', newline='') as f:
    headers = ['Song_Name', None, 'File_Name', ...]
    writer = csv.DictWriter(f, fieldnames=headers)
    writer.writeheader()
    # Now write a sample row:
    row = {'Song_Name': 'Dumb', 'Artist_Name': 'Nirvana'}
    write.writerow(row)  # Automatically skips missing keys

答案 1 :(得分:0)

正如Padraic Cunningham所说just insert into each row by index and write

with open('data.csv', 'r') as fdin, open('out.csv', 'w') as fdout:
    for line in csv.reader(fdin):
        # insert into each row by index
        line.insert(1, '')
        # and write
        csv.writer(fdout).writerow(newline)

答案 2 :(得分:0)

对于未来的读者,我发布了一个使用 Pandas 的替代方法,如果该模块可以读取 csv(就像在原始问题中一样)。

使用 Pandas 及其别名 pd,首先我们用 pd.read_csv 读取数据(指定分隔符 sep = ',')。然后,我们创建一个仅包含一个空列的 DataFrame (df)。我们在我们想要的位置的第一个 DataFrame 中 insert 此列。然后,我们再次使用 df.to_csv 将数据保存在 csv 中。让我们在代码中看到这一点,对于一个名为 test.csv 的 csv 文件:

import pandas as pd

# Read the file.
df = pd.read_csv('test.csv', header = None) 

# Create single (empty) column dataframe with the same number of rows as the original.
empty_col = pd.DataFrame(['']*len(df)) 

# Insert in original dataframe
df.insert(1, 'col1', empty_col) 
df.insert(4, 'col2', empty_col) 

# Save to csv
pd.to_csv('test.csv', index = False, header = False)

然后,我们在文件 test.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

请注意,我选择 header = None 是为了避免将第一行作为标题。我这样做是因为原始问题需要两列完全为空(包括标题),并且数据框不能有两列同名。在我们的例子中,我们为列指定的名称('col1'、'col2')无关紧要,因为我们不会将它们保存在文件中:我们在保存 csv 时指定 header = False

答案 3 :(得分:-1)

这是我的答案,可以帮助你。

首先,我建议在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)

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

相关问题