【问题标题】:Reading a csv file and writing rows to a second csv file in python that satisfy a condition读取一个csv文件并将行写入python中满足条件的第二个csv文件
【发布时间】:2019-07-05 05:53:45
【问题描述】:

问题是如何从一个 CSV 文件中读取文本、识别文件中的某个关键字、读取带有关键字的行,然后将这些行写入另一个文件。虽然这个问题在逻辑上看起来很简单,但在句法上却被证明具有挑战性。

下面的代码是我试过的代码。有趣的是, print(row) 行能够准确打印我试图写入第二个 CSV 文件的信息。但是,我无法使用 CSV 写入模块 (https://docs.python.org/3.3/library/csv.html) 完成相同的任务。

import csv

csvfile = open('read_file.csv', 'r')
read = csv.reader(csvfile)
for row in csvfile:
    if str('key_word') in row:
        #print(row)
        with open('write_file.csv', "w") as csv_file:
            writer = csv.writer(csv_file, delimiter=',')
            writer.writerow(row)

代码运行成功。但是,输出显得随机且杂乱无章。从本质上讲,迭代 CSV 文件并以有组织的逐行方式写入行似乎存在问题。

【问题讨论】:

  • 问题不清楚。请添加 csv 样本并解释使该行写入输出 csv 的条件是什么
  • 如果您在循环中以w 模式打开文件,那么您会删除以前的内容。您只需在开始时打开它一次,或者您必须使用模式a(附加)。

标签: python csv


【解决方案1】:

在迭代之前在不同的变量中打开这两个文件。不要每次循环迭代都打开目标文件。也不要使用for row in csvfile,使用for row in reader

import csv

csvfile = open('read_file.csv', 'r')
reader = csv.reader(csvfile)

with open('write_file.csv', "w+") as csv_file1: # different variable
    writer = csv.writer(csv_file1, delimiter=',')

    for row in reader:
        if str('key_word') in row:
            # print(row)
            writer.writerow(row)

【讨论】:

    【解决方案2】:

    您根本不需要使用csv 模块

    csvfile = open('read_file.csv', 'r')
    with open('write_file.csv', 'w+') as csv_file2:
        for row in csvfile:
            if str('key_word') in row:
                csv_file2.write(row)
    

    【讨论】:

      【解决方案3】:

      答案如下:

      with open('read_file.csv', 'r') as csv_file:
          csv_reader = csv.reader(csv_file)
      
      #skip first line
      #next(csv_reader)
      
      with open ('write_file.csv', 'w') as new_file:
          csv_writer = csv.writer(new_file, delimiter=',')
      
          for line in csv_reader:
              if str('keyword') in line:
              #print(line[2])
                  csv_writer.writerow(line)
      

      【讨论】:

        猜你喜欢
        • 2021-10-07
        • 2019-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-17
        • 2015-05-23
        • 1970-01-01
        相关资源
        最近更新 更多