问题是如何从一个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文件上进行迭代并以有组织的逐行方式写入行时似乎存在问题。
答案 0 :(得分:3)
在迭代之前用不同的变量打开两个文件。不要在每次循环迭代时都打开目标文件。也不要使用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)
答案 1 :(得分:1)
您根本不需要使用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)
答案 2 :(得分:0)
这是答案:
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)