如何在python中的不同目录中写入文件? [英] How to write file in a different directory in python?

查看:64
本文介绍了如何在python中的不同目录中写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 2.7.x 在 Linux 上工作,我正在通过终端运行一些 python 程序.我希望某些输出应该写入位于与我的工作目录不同的 目录中的文件中.所以我写了这段代码.但是,正在发生的是文件 All.txt 正在当前目录而不是所需目录中创建.有人可以帮助我哪里出错了吗?

I am working on Linux with python 2.7.x and I am running some programs python through terminal. I want the certain output should be written in a file located at different directory than my working directory. So I wrote this piece of code. However, what is happening is file All.txt is being created in current directory instead of the desired directory. Can someone help me where I went wrong?

ResultDir = '/pr/p1/ap11/' 
os.system('cd ' + ResultDir)
Outputname1 = 'All.txt'
Output1 = open(Outputname1, 'a')
Output1.write('hello' +'\n')
Output1.close()

推荐答案

使用 os.system 更改当前目录不会影响正在运行的 Python 进程.直接用完整路径打开文件即可:

Changing the current directory with os.system will not affect the Python process that’s running. Just open the file with its full path directly:

with open('/pr/p1/ap11/All.txt', 'a') as output:
    output.write('hello\n')

这篇关于如何在python中的不同目录中写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆