我的python代码出了什么问题,我正在尝试为文件添加实现多个文件搜索条件



我想更改我的代码,这样我就可以搜索多个输入文件并键入多个输入,比如说,如果我放在那里的输入文件中存在客户订单号7896547。为多个文件实现多个搜索条件的最佳方式是什么。

我的意思是四处提供,比如说50多个输入,1234567、1234568等等,还可以搜索多个文件(我的意思为10多个(。实现这一目标的最有效方法是什么?

我的代码:

import csv
data=[]
with open("C:/Users/CSV/salesreport1.csv", "C:/Users/CSV//salesreport2.csv") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)

name = input("Enter a string: ")
col = [x[0] for x in data]
if name in col:
for x in range(0, len(data)):
if name == data[x] [0]:
print(data[x])

else:
print("Does not exist")

我想我可以通过在open((部分添加一个文件名来添加输入吗?

在键入时也要添加多个输入,有没有办法不使用数组?

我的意思是identifierlist=["x","y","z"],不做这个

如注释中所述,您可以将CSV文件读取为数据帧,并使用df.srt.find()检查列中值的出现情况。

import pandas as pd
df = pd.read_csv('file.csv')  # read CSV file as dataframe 
name = input("Enter a string: ")
result = df["column_name"].str.findall(name)  # The lowest index of its occurrence is returned.

需要明确的是,您正在加载一些.csv,从用户那里获取一个名称,然后打印出列0中具有该名称的行?这似乎是Python字典的一个很好的用例,Python字典是Python中常见而简单的数据类型。如果你不熟悉,字典可以让你通过一些键来存储信息。例如,您可能有一个密钥"Daniel",它存储了一个名为Daniel的人的信息列表。在这种情况下,您可以遍历数组,并将每个人的行放入以名称为键的dict中。这看起来像:

names_dict = {}
for line in file:
//split and get name
name = split_line[0]
names_dict[name] = line

然后在dict中查找一个名字,你只需要做:

daniel_info = names_dict['Daniel']

或者更一般地,

info = names_dict[name]

您也可以使用dict来获取名称列表并检查名称是否存在,因为在Python中,dict有一个内置的方法来查找dict中是否存在键,";在"中;。你可以说:

if 'Daniel' in names_dict:

或者再次

if name in names_dict:

这个项目的另一个很酷的地方是让用户选择他们正在搜索的列。例如,让他们为该列输入3,然后搜索该行第3列中的任何内容、位置、电子邮件等。

最后,我将展示我将要做的事情的一个完整的具体例子:

import csv
##you could add to this list or get it from the user
files_to_open = ["C:/Users/CSV/salesreport1.csv","C:/Users/CSV//salesreport2.csv"]
data=[]
##iterate through list of files and add body to list
for file in files_to_open:
csvfile = open(file,"r")
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
keys_dict = {}
column = int(input("Enter the column you want to search: "))
val = input("Enter the value you want to search for in this column: ")
for row in data:
##gets the thing in the right column
v = row[column]
##adds the row to the list with the right key
keys_dict[v] = row
if val in keys_dict:
print(keys_dict[val])
else:
print("Nothing was found at this column and key!")

编辑:这里有一种方法可以编写大量的文本文件,并将它们组合成一个文件。对于多个输入,您可以要求他们键入逗号,如";丹尼尔、山姆、迈克;。。。然后用output.split(",").在这些逗号上分割输出。然后可以执行:

for name in names:
if name in names_dict:
##print them or say not found

你不能那样使用open
根据文档,每次调用只能传递一个文件。

鉴于您想要检查大量文件,这里有一个非常简单的方法示例,可以检查与此脚本相同文件夹中的所有CSV:

import csv
import os
data = []
# this gets all the filenames of files that end with .csv in the directory
csv_files = [x for x in os.listdir() if x.endswith('.csv')]
name = input("Enter a string: ")
# loops over every filename
for path in csv_files:
# opens the file
with open(path) as file:
reader = csv.reader(file)
for row in reader:
# if the word is an exact match for an entry in a row
if name in row:
# prints the row
print(row)

最新更新