def log():
with open("log.txt", 'a') as f:
print ".log.txt"
f.write(msg.encode('utf-8') +"\n")
I call log() several times but doesn't write each msg on new line, and I have no clue why. I tried adding f.close() at the end but that didn't work either. Super frustrating!
I assume you wanted to define log() as log(msg) :). I tried it and it worked on my system (OS X). \n should work, but it's not 100% cross platform so try using os.linesep instead.
# test.py
import os
def log(msg):
with open("log.txt", 'a') as f:
f.write(msg.encode('utf-8') + os.linesep)
log('aaa')
log('bbb')
Then:
$ python test.py
$ cat log.txt
aaa
bbb
You didn't given the msg.
def log():
msg="bhansa"
with open("log.txt", 'a') as f:
print ".log.txt"
f.write(msg.encode('utf-8') +"\n")
log()
or pass the msg in your method.
It's Working Fine.
Related
I want to get the console output in a .txt file.
This is what i have:
import sys
print('some text')
a='moretext.1'.split('.')
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()
here it works but in my program don't.
Does someone know what it could be?
It says that that its on line 2 or something
And I already searched on Stackoverflow and in the internet but i cant find anything
Do not mess with sys.stdout, instead open the file and print to it like so:
print('some text')
a='moretext.1'.split('.')
with open('output.txt', 'w') as out:
print(a, file=out)
Multiple ways to do so
1--
python3 myprogram.py > output.txt
2--
import sys
print('some text')
a='moretext.1'.split('.')
output = open('output.txt', 'w')
print(a, file=output)
output.close()
3--
import sys
print('some text')
a='moretext.1'.split('.')
stdout = sys.stdout
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()
sys.stdout = sys.__stdout__
4--
As #Timur Shtatland suggested you can use a with statement
I am using python 2.7, and currently, I have a python code that prints to screen. I have been piping the output from the python code to a file by using >> command in linux until now. I would like to know if there is a simple method of printing out the output to a file without having to change every print function. Is this possible in python?
def print1():
print "something1"
def print2():
print "something2"
...
def printN():
print "somethingN"
def main():
print1()
print2()
...
printN()
//I would like all the output to be in a file
Found a solution on : How to redirect 'print' output to a file using python?
Below works for my code:
import sys
orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
main()
sys.stdout = orig_stdout
f.close()
I am trying to put the output of these numbers into a file but I am failing a bit.
This is my code so far :
import os
import sys
with open('somefile.txt', 'rt') as f:
print('Hello World!')
os.system("pause")
num = int(input("Display multiplication table of? "))
for i in range(1,1000001):
print(num*i, file=f)
os.system("pause")
The programm says the = at file=f has a syntax error. Any1 know why?
Two things you did wrong:
- Didn't have f defined when you wrote to the file
- Didn't have the file opened as a write - you had it open as a read
After fixing them, the code executed perfectly!
import os
import sys
f = open('somefile.txt', 'wt') # CHANGED LINE
print('Hello World!')
os.system("pause")
num = int(input("Display multiplication table of? "))
for i in range(1,1000001):
print(num*i, file=f)
os.system("pause")
Normally when I write stdout to a file, I do it like this.
import sys
sys.stdout = open(myfile, 'w')
print "This is in a file."
Now, this method looks ugly to me, and I've heard here and there that there is a better method. If so, what is this better method?
You can also make use of the fact that print can actually wrote to a file.
with open("file.txt", "w") as f:
print("Hello World!", file=fd)
NB: This is Python 3.x Syntax only as print is a function in Python 3.x.
For Python 2.x you can however do:
from __future__ import print_function
Otherwise the same can be achieved with:
with open("file.txt", "w") as fd:
print >> fd, "Hello World!"
See: print() from Python 3.x Docs.
Print directly to the file, using either
with open(myfile, 'w') as fh:
fh.write("This is in a file.\n")
or
with open(myfile, 'w') as fh:
print >>fh, "This is in a file."
or
from __future__ import print_function
with open(myfile, 'w') as fh:
print("This is in a file.", file=fh)
You can do it as shown in the other answers, but it gets kind of old specifying the output file in every statement. So I understand the urge to just redirect sys.stdout. But yes, the way you propose doing it is not as elegant as it could be. Adding proper error handling will make it even uglier. Fortunately, you can create a handy context manager to address these issues:
import sys, contextlib
#contextlib.contextmanager
def writing(filename, mode="w"):
with open(filename, mode) as outfile:
prev_stdout, sys.stdout = sys.stdout, outfile
yield prev_stdout
sys.stdout = prev_stdout
Usage:
with writing("filename.txt"):
print "This is going to the file"
print "In fact everything inside the with block is going to the file"
print "This is going to the console."
Note that you can use the as keyword to get the previous stdout, so you can still print to the screen inside the with block:
with writing("filename.txt") as stdout:
print "This is going to the file"
print >> stdout, "This is going to the screen"
print "This is going to the file again"
it does work if I type this on python shell
>>> f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
>>> f.read()
'plpw eeeeplpw eeeeplpw eeee'
>>> f.close()
but if I create a python program, i doesn't work.
import os
f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
f.read()
f.close()
i saved this piece of code by using text editor.
if I execute this program in python shell, it shows nothing.
please tell me why..
In the interactive prompt, it automatically prints anything a function call returns. That means the return value of f.read() is printed automatically. This won't happen when you put it in a program however, so you will have to print it yourself to have it show up.
import os
f = open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
print f.read() # use print(f.read()) in Python 3
f.close()
Another suggestion I would make would be to use a with block:
import os
with open(os.path.join(os.getcwd(), 'test1.txt'), 'r') as f:
print f.read()
This means that you won't have to worry about manually closing the file afterwards.