Search code examples
pythoniovisual-studio-code

Script writes file in wrong directory


I just experienced a weird behaviour in Python.

I created a copy of a script.py file in a sub-folder within the folder that contains the initial script.

The script at the end exports some data into a .txt file by using:

with open('clayList.2203.txt', 'w',encoding='utf-8') as f:
 for item in claysUniqueList:
  f.write("%s\n" % item)

The problem is that Python writes the new file on the parent directory instead of the current one. I checked the path with:

print(sys.path[0])

and it prints the current path correctly.


Solution

  • By default, relative paths are relative to the working directory, that is the directory from which is run the command that run the script.

    If you want the path to be relative from the script directory, you will have to explicitly code this behaviour:

    import os
    
    filepath = os.path.join(os.path.dirname(__file__), 'clayList.2203.txt')
    with open(filepath, 'w',encoding='utf-8') as f:
        # ...