Home > OS >  error reading txt file as data frame that is selected from a list - python/pandas
error reading txt file as data frame that is selected from a list - python/pandas

Time:11-02

I'm currently learning - and I don't understand a lot of specifics about python/pandas. So, there may be an easy fix for this.

currently what I am trying to do is list txt files in a select directory and then be able to select them by number/index. Then for it to be read as a dataframe, for me to run data analysis against.

e.g

  1. user inputs directory -> code lists files in folder/directory
0.text.txt
1.text2.txt
  1. user should be able to select file by index/number
Select file number:
0
  1. and the selected file be passed as a dataframe.

Here is what i have tried so far:

#user inputs directory
input_dir = input(r'Enter location of INPUT folder: ')


#list filenames and select file by number selection.

filelist = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]

for cnt in range(len(filelist)):
       filename = filelist[cnt]
       print (cnt, filename)

choice = input("select file number: ")

# open the file based on the key input by user
df = pd.read_csv(filelist[int(choice)])

outputs:

0 test.txt
1 test2.txt

however i keep getting the corresponding error after selecting an index:

handle = open(
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

CodePudding user response:

df = pd.read_csv(f"{input_dir}/{filelist[int(choice)]}")

CodePudding user response:

you need to provide the path of the file

the other way to provide that is by using os.path.join(input_dir, f) like the one you use in the filelist = ...

So it will be like this

# open the file based on the key input by user
df = pd.read_csv(os.path.join(input_dir, filelist[int(choice)]))
  • Related