[英]Python search for string in csv columns and write row in another csv file
I'm fairly new to coding but I was trying to write a code that reads over a csv file to check if strings that the user inputs are in specific columns and then writes out the row in which the strings are present in a separate csv file.我对编码还很陌生,但我试图编写一个读取 csv 文件的代码,以检查用户输入的字符串是否在特定列中,然后在单独的 csv 文件中写出字符串所在的行. The issue is that when I run the code, it only prints out 1 row rather than multiple rows that have the strings within them.
问题是当我运行代码时,它只打印出 1 行而不是其中包含字符串的多行。 I also tried to make it case insensitive but somehow it doesn't work either.
我也试图让它不区分大小写,但不知何故它也不起作用。
My code right now looks like this:我的代码现在看起来像这样:
import csv
shape = input("Type in a shape ")
color = input("Type in a color")
with open("directory.csv", "r") as f:
csvreader = csv.reader(f, delimiter=",")
for row in csvreader:
if shape.lower() in row[7] and color.lower() in row[6] :
with open("data.csv", "w") as file:
writer = csv.writer(file, lineterminator = "\n")
writer.writerow(row)
Any help or suggestions are very much needed!非常需要任何帮助或建议!
pandas is here to help you. pandas 在这里为您提供帮助。 use the fragment below.
使用下面的片段。
import pandas as pd
df = pd.read_csv("directory.csv")
df1 = df[df["column1"] == shape & df["column2"] == color]
df1.to_csv("found_data.csv")
data.csv
is truncated every time it's opened in 'w'
mode, so it will only contain the final match. data.csv
每次以'w'
模式打开时都会被截断,因此它只会包含最终匹配。 Moving the open
statement to the beginning of the code fixes the problem.将
open
语句移到代码的开头可以解决问题。
import csv
shape = input("Type in a shape ")
color = input("Type in a color")
with open("directory.csv", "r") as f, open("data.csv", "w") as file:
csvreader = csv.reader(f, delimiter=",")
for row in csvreader:
if shape.lower() in row[7] and color.lower() in row[6] :
writer = csv.writer(file, lineterminator = "\n")
writer.writerow(row)
Alternatively, the file could be opened in 'a'
(append) mode, and then existing lines in the file will be preserved:或者,可以在
'a'
(附加)模式下打开文件,然后将保留文件中的现有行:
import csv
shape = input("Type in a shape ")
color = input("Type in a color")
with open("directory.csv", "r") as f:
csvreader = csv.reader(f, delimiter=",")
for row in csvreader:
if shape.lower() in row[7] and color.lower() in row[6] :
with open("data.csv", "a") as file:
writer = csv.writer(file, lineterminator = "\n")
writer.writerow(row)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.