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()
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With