0

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.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • `open(os.path.join(readDirectory, fileList[userInput]))`? – Green Cloak Guy Oct 02 '21 at 04:25
  • Are you asking how to open a file and print its contents? https://stackoverflow.com/questions/18256363/how-do-i-print-the-content-of-a-txt-file-in-python – Grismar Oct 02 '21 at 04:49
  • The question is how to open a file at a specific index position. I need to match the user input with the index file at that position and then open it to display the contents. – TheWanderingJedi Oct 02 '21 at 04:54

3 Answers3

1

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)
Pierre.Vriens
  • 2,117
  • 75
  • 29
  • 42
1

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%20path#os.path.join

yagya
  • 76
  • 3
0

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)
Mancitiss
  • 15
  • 2
  • 6