I am currently working on a project where I need to open a file at a specific index point. Here is my current code:
selectionInput == "2":
# Checks the current directory and opens the directory to read
currentDirectory = os.getcwd()
readDirectory = os.path.join(currentDirectory,r'Patients')
# Creates directory if it does not exist
if not os.path.exists(readDirectory):
os.makedirs(readDirectory)
# Creates file list to select file from
# List to store filenames
fileList = []
for file in os.listdir(readDirectory):
if file.endswith(".txt"):
fileList.append(file)
counter = 1
for fileName in fileList:
print("[%d] %s\n\r" %(counter, fileName))
counter = counter + 1
userInput = int(input("Please choose which file to open: "))
userInput = userInput - 1
At this point in the code, I have a list of the .txt files in the directory in the fileList. This list is displayed to the user in the following way:
Please choose which file to open:
- file1.txt
- file2.txt
- file3.txt ...etc
The user then inputs the number, which is decreased by 1 to match the index position. So if the user enters 1, 1 - 1 = 0, it should associate the input with the index position 0.
My question at this point is how do I use that index position to open the file and display the contents for the user?
For clarification, my question is not how to open and display the contents of a file, but how to use the user input to match a position on the index. Then use that index position to open the file associated with that position.