0

I would need to read a file from a list. Specifically, I would need to look for a file stored in a specific directory. Since it may happen to not remember all the files stored there or just the right name, I would need to list theirs. To do this step, I found this useful post:

How do I display the the index of a list element in Python?

Now I have a list like the following:

file=[]

for f in glob.glob("*.txt"):
    file.append(f)


for (num,item) in enumerate(file):
    print(num+1,item)        # updated after Thierry's comment

Output:

1 file 1.txt
2 file_2.txt
3 file_3.txt
...

I would like to read the file using

query=input("Please add your selection: ") # just the number
if int(query) in enumerate(datasets):
    dataset=pd.read_csv('path_name'+1) # I would need to add the path to the file and, by the number, the filename 
df = pd.DataFrame(dataset)

it gives me the error: TypeError: 'module' object is not iterable.

How could I do this?

still_learning
  • 776
  • 9
  • 32
  • 1
    The beginning of the answer you used is really bad advice. Don't use `index` that way. See the end of the answer or the other ones using `enumerate`. – Thierry Lathuille Apr 23 '20 at 19:05

2 Answers2

2

Like Thierry said in the comments, I would probably avoid that method and try something like this:

files = [f for f in glob.glob("*.txt")]

for fi, f in enumerate(files):
    print(fi, f)

query = input("Please add your selection: ") # just the number
df = pd.read_csv(files[int(query)])
Eric M
  • 1,360
  • 11
  • 19
  • Don't use list comprehensions for side effects: `[print()... for...]` uselessly creates a list of `None`s (the return values of the print functions). Use comprehensions when the goal is to create a list, write normal loops otherwise. See for example https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects – Thierry Lathuille Apr 24 '20 at 05:42
1

You could also try a slightly different approach using dictionaries.

import os
import pandas as pd

# iterate over a list of files in directory
filelist = [files for files in os.listdir("<path to directory>")]

# convert the files list to a dictionary
filelist_dict = { ind: name for (ind,name) in enumerate(filelist) }

# ask for user input
userinput = int(input("Enter a number :"))

# open the file based on the key input by user
with open(filelist_dict[userinput]) as file:
       df = pd.read_csv(file)  # read the csv file into a pandas dataframe
       print(df)               # print the dataframe

Hope this helps :)

Rishu Shrivastava
  • 3,745
  • 1
  • 20
  • 41
  • after selecting the query, how could I go back to the text? For example, if I select 4 and I want to see its corresponding text, would it be possible as well in the steps you showed me? I can open a new question if you prefer – still_learning Apr 23 '20 at 22:41
  • 1
    @still_learning if you want to open a file and read its content, then in the last section of the snip, instead of file.read(); you could read the csv file like pandas.read_csv("filename"). I have updated the code. check if this helps – Rishu Shrivastava Apr 24 '20 at 09:14
  • first of all thank you so much for answering me. I have tried your code, but I think I am doing something wrong because it is giving me an error. However, the main problem is that I cannot see the list of files, but only write the number to select. What I would like to understand if it would be possible, after selecting the number, trying to get back the filename, in order to create a new file just using 'file' (like stackoverflow.txt rather than 1). I am opening a new question: https://stackoverflow.com/questions/61415508/create-a-new-file-name-after-decoding-an-input-value – still_learning Apr 24 '20 at 18:55