I'm trying to write a Python script that searches a folder for all files with the .txt
extension. In the manuals, I have only seen it hardcoded into glob.glob("hardcoded path")
.
How do I make the directory that glob searches for patterns a variable? Specifically: A user input.
This is what I tried:
import glob
input_directory = input("Please specify input folder: ")
txt_files = glob.glob(input_directory+"*.txt")
print(txt_files)
Despite giving the right directory with the .txt
files, the script prints an empty list [ ]
.
If you are not sure whether a path contains a separator symbol at the end (usually '/'
or '\'
), you can concatenate using os.path.join
. This is a much more portable method than appending your local OS's path separator manually, and much shorter than writing a conditional to determine if you need to every time:
import glob
import os
input_directory = input('Please specify input folder: ')
txt_files = glob.glob(os.path.join(input_directory, '*.txt'))
print(txt_files)