Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write file in a different directory in python?

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()
like image 298
b2850624 Avatar asked Mar 02 '26 19:03

b2850624


1 Answers

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')
like image 193
poke Avatar answered Mar 05 '26 08:03

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!