Home > Software engineering >  Python cannot find exiting path
Python cannot find exiting path

Time:02-15

While preparing my dataset for a machine learning model I stumbled upon a bug (at least from my perspective). I was trying to move files around in Windows 10 but my system always told me that my file does not exist (FileNotFoundError: [Errno 2] No such file or directory: '../path/to/file'), but I specifically probed for the file before which returned True.

What I was trying in my IPython console was the following (which can reproduce the bug):

import os
import shutil

path = '../path/to/file'            # You can see I use relative paths
out_path = '../path/to/out/'

os.makedirs(out_path)               # Make sure paths do exist
_, name = os.path.split(path)
out_path  = name

# Produces almost the same error FileNotFoundError: [WinError 3] The system cannot find the given directory: path
# os.rename(path, out_path)
shutil.move(path, out_path)

You obviously need a file to move at '../path/to/file'. I tested whether I use the correct path with os.path.exist(path) which returned True.

Do I simply misread the documentation and the usage is different to what I am thinking? I understood it like the first argument is the path to the file to move and the second one is the path for the file after moving it. Or is there really a bug in my Python environment?

I also tried moving the file with absolute paths returned by os.path.abspath(), but this did not work either.

FYI: I am using Windows 10 and Python 3.8.12.

Edit: I found the mistake I did... After 2.5 days of labeling image data it appears like I had an underscore mistaken for a hyphen which is why my output directory seems to be malformed... :/

CodePudding user response:

You are not doing a relative path to the current directory, but to the parent directory of the current directory with a double dot '../path' and not single dot './path'. So if your files aren't in the parent directory of the current directory, they won't be found.

When you try to append the file name to the directory path "out_path" you do a string append. which just makes a new file with the combined names rather than move the file into the directory. Use the os.path.join() function for this.

Here is code I made that corrects these two points and works on my end.

import os
import shutil

path = './somefile.txt'            # CORRECTED: One dot for current directory
out_path = './somedir'

try:
    os.makedirs(out_path)               # Make sure paths do exist
except Exception as e:
    print(e)

_, name = os.path.split(path)
out_path = os.path.join(out_path, name) # CORRECTED: Use appropriate function

# Produces almost the same error FileNotFoundError: [WinError 3] The system cannot find the given directory: path
# os.rename(path, out_path)
shutil.move(path, out_path)

CodePudding user response:

Are you using the full path? as in "C:\Users..\path\to\file" ?

  • Related