繁体   English   中英

如何修改我的代码,以便我可以在 Python 中同时搜索多个输入(来自同一列)

[英]How to I modify my code so I can search for multiple inputs(from the same column) at the same time in Python

所以它涉及我之前发布的一个问题,我得到了很多很好的答案。 但是对于这种情况,我想在提示下同时输入多个输入,并搜索 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 列中搜索世界“leet”、“hello”和数字 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}')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM