简体   繁体   中英

What is wrong my python code, I'm trying to add implement multiple file search criteria for files

I want to make changes in my code so I can search for multiple input files and type multiple inputs, let's say if client order number 7896547 exist in the input file I put there. What is the best way to implement multiple search criteria for multiple files.

What I meant is giving around let's say like more than 50 inputs, 1234567, 1234568 etc...…, and also search through multiple files(I mean more than 10). What is the most efficient way to achieve this?

My code:

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")

I thought I can just add input by adding one file name in the open() part?

Also to add multiple input when typing, is there way to not use array?

I mean identifierlist = ["x","y","z"], not doing this

As mentioned in comments, you can read CSV file as a dataframe and use df.srt.find() to check occurrence of a value in a column.

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.

Just to be clear, you are loading in some .csvs, getting a name from the user, and then printing out the rows that have that name in column 0? This seems like a nice use case for a Python dictionary, a common and simple data type in Python. If you aren't familiar, a dictionary lets you store information by some key. For example, you might have a key 'Daniel' that stores a list of information about someone named Daniel. In this situation, you could go through the array and put everyone row into a dict with the name as the key. This would look like:

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

and then to look up a name in the dict, you would just do:

daniel_info = names_dict['Daniel']

or more generally,

info = names_dict[name]

You could also use the dict for getting your list of names and checking if a name exists, because in Python dicts have a built in method for finding if a key exists in a dict, "in". You could just say:

if 'Daniel' in names_dict:

or again,

if name in names_dict:

Another cool thing you could do with this project would be to let the user choose what column they are searching. For example, let them put in 3 for the column, and then search on whatever is in column 3 of that row, location, email, etc.

Finally, I will just show a complete concrete example of what I would do:

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!")

EDIT: here's a way to write a large number of text files and combine them into one file. For the multiple inputs, you could ask them to type commas, like "Daniel,Sam,Mike"... and then split the output on these commas with output.split(","). You could then do:

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

You can't use open like that.
According to the documentation , you can only pass one file per each call.

Seeing as you want to check a large number of files, here's an example of a very simple approach that checks all the CSVs in the same folder as this script:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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