mkdr27 mkdr27 - 3 months ago 8
Python Question

Output of print to file Inside script | Python

I simply need to run the python[V:2.6] script as ./test.py.
The output of print(a) which is 'hello world', should be saved into "file.txt"
how can i do this inside the python script?
I know,

./test.py > file.txt


test.py

#!/usr/bin/python
a = 'hello world'
print(a)
f = open('/root/file.txt', 'w')

Answer
#!/usr/bin/python
a = 'hello world'
f = open('/root/file.txt', 'w')
print >>f, a

now "hello world" will be printed in file.txt while running ./test.py This is simple but might be helpful for python beginners.