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()
b2850624
  • 153
  • 1
  • 1
  • 6
  • 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.) – Cameron Nov 21 '14 at 23:17

1 Answers1

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')
poke
  • 369,085
  • 72
  • 557
  • 602
  • do I need to mention some output stream object closing statements? As I wrote in my code `Output1.close()`? – b2850624 Nov 21 '14 at 23:23
  • @b2850624 No, if you use the `with` statement like that, the file will be automatically closed. – poke Nov 21 '14 at 23:27