Home > front end >  Have user choose specific file and open it
Have user choose specific file and open it

Time:08-03

I want to have the user choose a file with python, something along the lines of:

def get_file_input():
    file = getFile()
    return file

file = open(file,"r").readlines()

an return the value of the text file in a list, so it's easy to loop through?


Example: File.txt:

Hel
lo
Wor
ld

and then user selects File.txt

and return ["Hel", "lo", "Wor", "ld"]

CodePudding user response:

You can use os.listdir() to get the names of all files in the current directory. You can print that to the user and have them type one of the names to select the file. Or you could assign each a number and have the user choose by typing that number.

import os

print("Available files:\n", os.listdir())
file_name = input("Type which of the above files you want to open: ")

With numbers:

import os

available_files = os.listdir()
print("Available files:")
for number, file in enumerated(available_files):
   print(f"{number}: {file}")

file_nbr = int(input("Which number to open: "))
# You should check if file_nbr isn't out of bounds here
file_name = available_files[file_nbr]

CodePudding user response:

If you want somethings that does what I get from your question then:

import os

filename = input() #File.txt
with open(filename) as f:
    lines = f.readlines()
    print(lines)

If you want to remove the '\n' (noting the spaces) then you can use this too

import os

filename = input() #File.txt
with open(filename) as f:
    lines = list(f.read().split('\n'))
    print(lines)

*Sorry if I misunderstood you question

  • Related