1

I am writing a python code that scans the subdirectories for files, and based on a list it has (csv file), it checks if the files exist or not.

So far, I can get the absolute path, and then join it with a string, if I do:

    base_dir = os.path.abspath(os.path.dirname(__file__))
    csv_path = os.path.join(my_path, csv_filename)

And I can successfully locate my csv and pass it through pandas or the csv reader from Python.

However, when I go through my csv where the filenames are (which are correct), and then try and do:

    base_dir = os.path.abspath(os.path.dirname(__file__))
    full_path = os.path.join(base_dir, path, filename)
  • Note that path is the a subdirectory, and filename is the actual filename I want to check.

When I output the base_dir and full_path, I get the following, respectively:

    /home/myname/projectFolder
    /subfolder/filename.extension

instead of having:

  /home/myname/projectFolder/subfolder/filename.extension

Something is obviously wrong with what's happening. I need the complete filepath to run os.path.exists() to see if the file is there or not, but since what I get with the full_path is just the relative path,

I don't know how to proceed.

Dvyn Resh
  • 980
  • 1
  • 6
  • 14
Razgriz
  • 7,179
  • 17
  • 78
  • 150

2 Answers2

4

From the documentation of os.path.join:

[...] If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

So most likely path starts with a slash, i.e. path = "/subfolder" and hence the previous base_dir is discarded.

a_guest
  • 34,165
  • 12
  • 64
  • 118
3

If the stings start with the / then it would consider it as an absolute path and that is not desired.

So try to remove the slash from the beginning of the string.

I've found another stackoverflow link which may help you:

Why doesn't os.path.join() work in this case?

For the final result you just need to try not to have the slash in your path.

Alireza HI
  • 1,873
  • 1
  • 12
  • 20