-2

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')
mkdr27
  • 37
  • 9
  • you never call input so I would start by fixing that. – Padraic Cunningham Sep 04 '16 at 14:59
  • @Padraic I didn't mention input as a function. it is just a string. I changed that to 'hello world'. and it is not duplicate. The duplicate mentioned takes input from user but in this script it is declared inside the script. – mkdr27 Sep 07 '16 at 05:36

2 Answers2

0

better solution : Python print statement got keyword param named file

print('spam', file=<YOUR FILE>)
Take_Care_
  • 1,957
  • 1
  • 22
  • 24
-2
#!/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.

mkdr27
  • 37
  • 9
  • 2
    Please don't answer questions with Python2 unless they are explicitly tagged that way. It's way too old to be assuming that's the default. – Two-Bit Alchemist Sep 04 '16 at 13:57
  • 1
    @Two-BitAlchemist I disagree. Either Python 2 or Python 3 are possible if no version is specified – pppery Sep 04 '16 at 14:28
  • @Mani Could you please add some context to your code? – pppery Sep 04 '16 at 14:28
  • @ppperry It's very easy to use the print function in Python 2 (`from __future__ import print_function`), but not the other way around. At any rate, the *question* uses Python 3 syntax. – Martin Tournoij Sep 04 '16 at 14:58