从列表位置打开文件

Opening a file from list position

我目前正在做一个项目,我需要在特定的索引点打开一个文件。这是我当前的代码:

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 文件的列表。此列表以下列方式显示给用户:

请选择要打开的文件:

  1. file1.txt
  2. file2.txt
  3. file3.txt ...等等

然后用户输入数字,数字减 1 以匹配索引位置。所以如果用户输入1, 1 - 1 = 0,它应该将输入与索引位置0相关联。

此时我的问题是如何使用该索引位置打开文件并为用户显示内容?

澄清一下,我的问题不是如何打开和显示文件的内容,而是如何使用用户输入来匹配索引上的位置。然后使用该索引位置打开与该位置关联的文件。

恕我直言,您不需要使用计数器系统,您把它搞得太复杂了。在使用输入来确定要打开哪个索引之前,最好对任何人工输入减一。

下面演示了如何实现它以及您所要求的内容:

import os

#used in my test case to get my current working directory
cwd = os.getcwd()

#get your list of files from your cwd
files = os.listdir(cwd)

#simulated human input with 0 indexing fix
human_input = 5
human_input = human_input - 1 #this is the fix that removes the need for your counter :)

#this is the bit you actually asked for :) it will open the file read it then print to the console
filechosen = open(files[human_input], "r")
readfile = filechosen.read()
print(readfile)

我猜你想从不同的目录打开文件,所以这就是我根据你的代码所做的

fileDirectory = os.path.join(readDirectory, fileList[userInput])
file = open(fileDirectory, "r")
readfile = file.read()
print(readfile)

您只需要使用 user_input 作为索引从 fileList 中 select 文件,然后将路径与 readDirectory 连接以获得用户 select 文件的完整路径编辑

由于 for 循环将按顺序进行,并且您正在使用计数器(序号)打印文件索引,只需使用用户输入(减 1)即可为您提供正确的文件。

  readDirectory = os.path.join(currentDirectory,r'Patients')
  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

#This should work to achieve your outcome.

selected_file = os.path.join(readDirectory, fileList[userInput])
with open(selected_file, 'w') as f:
    //do something, use 'a' for append and 'r' for reading contents

更多详细信息,请参阅读写文件文档:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files 并在 https://docs.python.org/3/library/os.path.html?highlight=join%20path#os.path.join

加入路径文档