Home > Mobile >  Opening a file from list position
Opening a file from list position

Time:10-02

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:

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

Thank you for the help!

CodePudding user response:

You will simply need to select the file from the fileList using user_input as the index and then join the path with readDirectory to get the full path of file the user selected.

Since for loop will go sequentially and you are using counter (sequential number) for printing file index, simply using user input (less 1) will give you the correct file.

  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

Refer Reading and writing files docs for more details: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files and Join Path docs at https://docs.python.org/3/library/os.path.html?highlight=join path#os.path.join

CodePudding user response:

I guess you want to open files from a different directory, so this is what I've made based on your code

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

CodePudding user response:

You don't need to use your counter system IMHO, you're over complicating it. You'd do better to just like minus one to any human input before you're using the input to determine which index to open.

The below demonstrates how you could implement it along with what you've asked for:

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)
  • Related