Python:在forloop中写入CSV,有条件地在特定列中添加值

2024-06-07 08:59:48 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的CSV文件内容的示例:

Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,

我想遍历CSV文件的内容,根据一个测试(CSV数据的外部性,使用提供给封闭函数的输入值),最终得到如下结果:

^{pr2}$

我当前的代码如下:

csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.

使用CSV模块或pandas一次性添加新数据是很容易的,但是这里我需要迭代地添加数据。似乎我无法在适当的地方更改CSV文件(?),但如果我写到一个不同的CSV文件,它将覆盖循环中的每个匹配项,因此它将只反映该值。在


Tags: 文件csv数据in示例内容appledata
3条回答

基本上有两种方法:

在打开第二个文件之前,在第二个文件循环之前附加第一行。完成所有行后,关闭初始文件。示例:How do you append to a file?

2-从初始csv读取所有内容。然后对您创建的对象进行更改(我强烈建议使用Pandas进行此操作)。然后写一个csv。下面是该方法的一个示例:

import pandas as pd
import numpy as np

# read in the csv
csv_data = pd.read_csv('./data/fruit_data.csv')

# I'm partial to the numpy where logic when creating a new column based 
# on if/then logic on an existing column
csv_data['ripe'] = np.where(csv_data['fruit']==input, True, False)

# write out the csv
csv_data.to_csv('./data/outfile.csv')

在1和2之间的选择应该是真正的尺度。如果你的csv太大了,以至于你不能按你想要的方式读取和操作它,那么你应该逐行修改它。如果你能读懂整件事,然后用熊猫来操纵,你的生活就会轻松多了。在

如果创建临时文件,则可以在读取行时写入这些行。如果在Unix上使用os.rename,则,“the renaming will be an atomic operation”:

import csv
import os

def update_fruit_data(input):
    csv_file_name = 'data/fruit_data.csv'
    tmp_file_name = "%s.tmp" % csv_file_name
    # Update fruit data
    with open(csv_file_name, 'r') as csv_input_file:
        csv_reader = csv.reader(csv_input_file)
        with open(tmp_file_name, 'w') as csv_output_file:
            csv_writer = csv.writer(csv_output_file)
            for row in csv_reader:
                fruit = row[0]
                if fruit == input:
                    row[2] = 'true'
                csv_writer.writerow(row)
    # Rename tmp file to csv file
    os.rename(tmp_file_name, csv_file_name)

while True:
    input = get_input()
    update_fruit_data(input)

这里的get_input是用来获得input值的任何东西的替代物。在

如果要创建新的CSV文件

csv_data = csv.reader(open('./Desktop/fruit_data.csv', 'r'))
csv_new = csv.writer(open('./Desktop/fruit_new_data.csv', 'w'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
        row.append("ripe")
        csv_new.writerow(row)
    else:
        csv_new.writerow(row)

基本上,上一个问题中唯一缺少的就是最后一个陈述,也就是写,否则就是在标准不匹配的情况下添加。在

另一种可能是使用linestartswith

相关问题 更多 >

    热门问题