所以这涉及到我之前发布的一个问题,我得到了很多好的答案。但在这种情况下,我想在提示下同时输入多个输入,并在csv文件列表中搜索。
例如:
Enter your strings:
11234567, 1234568. 1234569 etc.
(我想将参数设置为从1到20(
至于文件输入,有没有一种方法可以用CSV搜索具有文件扩展名的整个文件夹,而不是在我的代码中硬编码CSV文件的名称?这样一来,我就不必在代码中不断添加CSV文件的名称,比如说,如果想搜索50个文件的话。Python中有类似脚本的功能吗?
仅供参考,我输入的每个输入值都是不同的,因此它不能同时存在于2个或多个csv文件中。
代码:
import csv
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:
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!")
还有最后一件事,我如何显示csv文件的名称作为结果?
Enter the column to search: 0
Enter values to search (separated by comma): 107561898, 107607997
['107561898', ......]
Process finished with exit code 0
107561898是来自文件1的第0列,107607997是存储在文件2(第0列(中的第二个值
正如您所看到的,结果只是返回包含第一个输入的文件,我希望在其中返回两个输入,所以两个记录第0列是所有输入值(卡号(的
鉴于您想要检查大量文件,这里有一个非常简单的方法示例,可以检查与此脚本位于同一文件夹中的所有CSV。
此脚本允许您指定要搜索的列和多个值
样本输入:
Enter the column to search: 2
Enter values to search (separated by comma): leet,557,hello
这将在第3列中搜索世界";韭菜"你好";以及数字557。
请注意,列从0开始计数,并且除非关键字本身具有空格字符,否则不应存在多余空格。
import csv
import os
# this gets all the filenames of files that end with .csv in the specified directory
# this is where the file finding happens, to answer your comment #1
path_to_dir = 'C:\Users\Public\Desktop\test\CSV'
csv_files = [x for x in os.listdir(path_to_dir) if x.endswith('.csv')]
# get row number and cast it to an integer type
# will throw error if you don't type a number
column_number = int(input("Enter the column to search: "))
# get values list
values = input("Enter values to search (separated by comma): ").split(',')
# loops over every filename
for filename in csv_files:
# opens the file
with open(path_to_dir + '\' + filename) as file:
reader = csv.reader(file)
# loops for every row in the file
for row in reader:
# checks if the entry at this row, in the specified column is one of the values we want
if row[column_number] in values:
# prints the row
print(f'{filename}: {row}')