简体   繁体   中英

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.

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:
    # ...

When you run code in Visual Studio, there are debugging options. One of these it the directory to run from, called "Working directory". (Right click your project and go to settings).

To run from the sub-directory you need to change this. If you want to start in a sub directory, type that in instead, in the "working directory" shown here:

在此处输入图片说明

path for creating the file should be relative to the directory of execution

eg your pwd is parent and your script is in parent/child1/child2/script.py then path of the file to be created should be ./child1/child2/clayList.2203.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM