MagicGAT
MagicGAT

Reputation: 135

Why is the `open()` function expecting a directory?

Im trying to open and read a number of files so that I can search through and, extract parts of them using some regular expressions. However, I cannot get Python/PyCharm to open the files

The folder containing the files is in the Interpreter's PATH list. Initially the error was (PATH that I passed) DOES NOT EXIST. So, I added the first file itself to the Interpreter's PATH list. Now it raises a different error, that PATH does not lead to a directory

  stack = os.listdir(
  "/Users/gregorytaylor/Documents/software_development/my_python_code/random/countries"
)

for entry in stack:

  # opens and reads file within `contents` variable
file_path = (
     "/Users/gregorytaylor/Documents/software_development/my_python_code/random/countries" + "/" + entry + "/"

  )

  selection = open(file_path, "rt")
  contents = read(selection)

This is the error I received:

Traceback (most recent call last):
  File "/Users/../PycharmProjects/eu4_country_text_extraction/venv/completed_code", line 34, in <module>
    selection = open(file_path, "rt")
NotADirectoryError: [Errno 20] Not a directory: '/Users/../Documents/software_development/my_python_code/random/countries/TRI - Trier.txt/'

Am I making a mistake in my function selection or passing the arguments? Stumped.

Upvotes: 0

Views: 1391

Answers (3)

Trenton McKinney
Trenton McKinney

Reputation: 62383

Code with exception handling

from pathlib import Path

p = Path('/Users/gregorytaylor/Documents/software_development/my_python_code/random/countries')

for entry in stack:
    f_p = p / entry  # entry is a file name in stack; add entry to path p
    print(f_p)  # if you want to see what you're opening
    if f_p.is_file():  # checks that you've provide a file and not a path
        try:
            with f_p.open('rt') as f:
                contents = f.read()
                print(contents)
        except Exception as e:
            print(e)

Upvotes: 0

SyntaxVoid
SyntaxVoid

Reputation: 2623

Don't stress yourself over building your own paths. There's a builtin module that can do it for you and is platform independent (it will work on Windows, Linux, and Mac)

Instead of doing file_path = "/Users/randomfolder" + "/" + entry + "/", import os and use the os.path.join method. (And as mentioned in the other answer, the problem is the final "/" you add at the end)

import os

root_path = "/Users/gregorytaylor/Documents/software_development/my_python_code/random/countries" 
stack = os.listdir(root_path)

for entry in stack:
  # opens and reads file within `contents` variable
  file_path = os.path.join(root_path, entry)  # <-- Will properly format the path
  if not os.path.isfile(file_path): # Skip anything that isn't a file
    continue # Continue will jump to the top of the loop and begin the next iteration
  selection = open(file_path, "rt")
  contents = read(selection)

Upvotes: 0

rems4e
rems4e

Reputation: 3172

You have a stray / in the path you try to open. A file can't have one at the end, so just remove it.

By the way, The PATH variable does not have anything to do with opening a file, you don't have to set it.

Upvotes: 1

Related Questions