我正在使用 Python 2.7.x 在 Linux 上工作,我正在通过终端运行一些 Python 程序。我希望某些输出应该写入位于不同 目录而不是我的工作目录的文件中。所以我写了这段代码。但是,正在发生的事情是在当前目录而不是所需目录中创建文件 All.txt。有人可以帮助我哪里出错了吗?
ResultDir = '/pr/p1/ap11/'
os.system('cd ' + ResultDir)
Outputname1 = 'All.txt'
Output1 = open(Outputname1, 'a')
Output1.write('hello' +'\n')
Output1.close()
请您参考如下方法:
使用 os.system 更改当前目录不会影响正在运行的 Python 进程。直接打开带有完整路径的文件:
with open('/pr/p1/ap11/All.txt', 'a') as output:
output.write('hello\n')
