【问题标题】:Opening a file from list position [duplicate]从列表位置打开文件[重复]
【发布时间】: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 文件的列表。该列表以下列方式显示给用户:

请选择要打开的文件:

  1. file1.txt
  2. file2.txt
  3. 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


【解决方案1】:

您只需使用 user_input 作为索引从 fileList 中选择文件,然后将路径与 readDirectory 连接,即可获取用户选择的文件的完整路径。

由于 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 加入 Path 文档

【讨论】:

    【解决方案2】:

    恕我直言,您不需要使用您的计数器系统,您将其复杂化了。在使用输入来确定要打开哪个索引之前,最好对任何人工输入进行减一。

    下面演示了如何按照您的要求实现它:

    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)
    

    【讨论】:

    • 我真的很喜欢你的回答。但是,我还使用计数器来显示用户选择的数字。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多