Python 3:在相对目录中创建文件

Com*_*orn 1 python directory operating-system file python-3.x

我想在与Python项目相同的文件夹中创建一个新目录,并希望在该位置创建一个新的文本文件。

我怎样才能做到这一点,而不使用绝对目录名称?

amo*_*136 5

假设您具有相对于调用脚本的位置的python项目目录,并且还具有要在其中创建文件夹的绝对目录,或者相对于您从其调用脚本的位置,请参见以下内容:

import os

rel_directory=os.path.relpath(target_directory,base_directory)
Run Code Online (Sandbox Code Playgroud)

在这里,第二行返回从base_directory到target_directory的相对路径。

如果需要当前的工作目录,可以执行os.path.relpath('.','/')os.path.realpath('.')os.getcwd()。如果您在脚本启动后不更改当前工作目录,则它们都是相同的。

从那里,您只需在零件前面添加适当的相对目录即可打开文件。

f=open(rel_directory+'/'+filename,'a')
f.write("some stuff I'm adding to the file")
f.close()
Run Code Online (Sandbox Code Playgroud)