What is the proper way to handle an incorrect directory path taken as user input?

StackOverflow https://stackoverflow.com/questions/22939211

  •  29-06-2023
  •  | 
  •  

Вопрос

Below is a snippet of code I am trying to use to take a directory path as "raw input" from the user. I receive the following error after the input is taken from the user:

Traceback (most recent call last):
  File "C:\Users\larece.johnson\Desktop\Python Programs\Hello World 2", line 14, in <module>
    f = open(path, "r+")
IOError: [Errno 2] No such file or directory: 'C:/Users/larece.johnson/Desktop/Python Programs/BostonLog.log.2014-04-01'

Notice that the .log file ending is missing from the user input.

For example, the directory and file I'm looking for is

C:/Users/larece.johnson/Desktop/Python Programs/BostonLog.log.2014-04-01.log

But the user entered

C:/Users/larece.johnson/Desktop/Python Programs/BostonLog.log.2014-04-01

Is there a particular way I am supposed to take the path from user so that Python accepts it?

This was my original code:

#f = open("C:/Users/larece.johnson/Desktop/BostonLog.log.2014-04-02.log", "r+")

# User will enter the name of text file for me
path = raw_input("Enter the name of your text file: ")
f = open(path, "r+")
Это было полезно?

Решение

I think you should try something like:

from pathlib import Path

user_input = Path(input("Enter the path of your file: "))
 
if not user_input.exists():
    raise ValueError(f"I did not find the file at {user_input}")
with open(user_input, "r+") as iof:
    print("Hooray we found your file!")
    #stuff you do with the file goes here

Другие советы

It seems you want to check if the directory exists.

If so, see os.path.isdir.

os.path.isdir(path)
    Return True if path is an existing directory.
    This follows symbolic links, so both islink()
    and isdir() can be true for the same path.

You can do like this:

s = raw_input();
if os.path.isdir(s):
    f = open(s, "r+")
else:
    print "Directory not exists."

I figured it out... I forgot to add the file extension at the end of the file name on my directory path; I did not notice that I was cutting it off by just copying/pasting the name of my file.... the program works now... thank you all!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top