Get the name of a file in a folder

Hi,

I want to get the name of a file in a folder and then read the data (it is an image). I have written:

name1 = input("Enter path of original image: ")
path = name1
print(“path:”, path)
filename = os.path.basename(path)
print(“file name:”, filename)
img = io.imread(filename)

Unfortunately, the file name is the name of the folder containing the image. Obviously, io.imread does not read folders. Any idea about how to solve this problem.

Thanks,
Antonio

I suppose that the users of your program quite literally interpret the command “Enter path of original image”. I mean they give the name of a directory where the image is located :wink:

os.path.basename is not able to know if a given name is a name of a directory or a regular file. You have to check for that first by, for example, calling os.path.isdir(...).

You need the path to the file, not its basename.

Suppose the file is in /user/Pictures/selfie.png then that is the path you must use.
But you code change that to be only selfie.png without the very important Pictures folder part. Which assuming you are in the /user folder will look for /user/selfie.png

So what you need to do is:

img = io.imread(path)

It’s not really clear what this means. From the code that you showed, it looks like you want the users to type a path, and then get a filename from it.

But… why?

If the user typed an absolute path (i.e, including the name and all the folders to navigate, starting at the top of the filesystem), or at least a complete relative path (it will be relative to the current working directory) then that is already what io.imread wants (and just what open would want, or really anything else that uses files): the point is to tell it which file, and also where to find it.

If the user only types a name, then the program has to have its own rules to decide where the file is. A filename by itself is already a relative path (it just means “in the current working directory”).

Since there are print calls in your code already, I assume you already tried testing the code and looking at the output. When you say “Unfortunately, the file name is the name of the folder containing the image.”, that sounds like the problem is simple: os.path.basename takes the path to the image, and gets rid of the image name, leaving only the folder name. But now I’m confused: didn’t you already see the result you want, from the print("path:", path) part? Or did you think that it should be changed somehow?

It would help if you could show some examples of what the user types, and what you think should happen as a result.