7
file_name=[]
user_input= input('File name: ')
while user_input != "":
    part_name.append(user_input)
    user_input = input('File Name: ')

measure_list=[]    
for f in file_name :
    with open("/Users/Desktop/File/%s.txt" %f ,"r",encoding="UTF-16") as read_file:

This is my existing code currently. It takes user input in to search for a file as specified by the user, then adds that file to a list, and through a loop opens each file one by one. I would like to try and make this more automatic, so that the script will automatically grab all of the files in a given folder for this process, instead of the user having to input the name for each file. Any suggestions on how to make this more automated?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Have you had a look at the [glob module](https://docs.python.org/3/library/glob.html) and [os.listdir](https://docs.python.org/3/library/os.html#os.listdir)? – janbrohl Aug 17 '16 at 16:57
  • Thank you John Sharpe, thought I looked hard enough before asking this question, but I guess I need to a bit more digging next time – Chase Garfield Aug 17 '16 at 18:21

2 Answers2

2

Use os.listdir:

for f in os.listdir("/Users/Desktop/File/"):
    with open(f, "r", encoding="UTF-16") as read_file:

Use glob.glob instead to select only files matching a given pattern:

for f in glob.glob("/Users/Desktop/File/*.txt"):
    with open(f, "r", encoding="UTF-16") as read_file:
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You can use a new Python library pathlib instead:

from pathlib import Path

p = Path.cwd() 
files = [x for x in p.iterdir()]
for file in files:
    with open(str(file), 'r', encoding="UTF-16") as f:
        # ....