2

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()
1
  • Your call to os.system starts a new shell, changes its working directory, and then promptly destroys the shell. At no point is the working directory of your script set. (You can use os.chdir() if you want to do that.) Commented Nov 21, 2014 at 23:17

1 Answer 1

13

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')
Sign up to request clarification or add additional context in comments.

2 Comments

do I need to mention some output stream object closing statements? As I wrote in my code Output1.close()?
@b2850624 No, if you use the with statement like that, the file will be automatically closed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.