【发布时间】:2021-11-23 13:52:33
【问题描述】:
我目前正在处理一个需要在特定索引点打开文件的项目。这是我当前的代码:
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
此时在代码中,我在fileList 的目录中有一个.txt 文件的列表。该列表以下列方式显示给用户:
请选择要打开的文件:
- file1.txt
- file2.txt
- file3.txt ...等
然后用户输入数字,该数字减 1 以匹配索引位置。所以如果用户输入 1, 1 - 1 = 0,它应该将输入与索引位置 0 相关联。
此时我的问题是如何使用该索引位置打开文件并为用户显示内容?
为了澄清,我的问题不是如何打开和显示文件的内容,而是如何使用用户输入来匹配索引上的位置。然后使用该索引位置打开与该位置关联的文件。
【问题讨论】:
-
open(os.path.join(readDirectory, fileList[userInput]))? -
您是在问如何打开文件并打印其内容吗? stackoverflow.com/questions/18256363/…
-
问题是如何在特定索引位置打开文件。我需要将用户输入与该位置的索引文件匹配,然后打开它以显示内容。
标签: python python-3.x list arraylist