Is there any difference in the code below?
file=open("sample.txt", "w", encoding="utf-8")
print("hello", file=file)
file.write("hello")
file.close()
Python 3 allows you to write files with print statements, but are there any situations where you can use them differently?
python python3
It looks the same in terms of output (write) to a file, but if you look closely, it seems that there are the following differences:
print —By default, a new line is added to the end of the output (changeable).
write —Outputs the passed string as it is.You can only receive strings.
In the case of write, when repeated, the output is as follows:
write("Hello")
write ("Hello")
write ("Hello")
# = > Hello Hello Hello
Note:
Python Tips:I want to print a string without a new line
Are there any situations where you can use it differently?
write
is faster than print
.
I think it's about 1.5 to 3 times faster in a simple case like the question.
Also, print
cannot be used for file objects that are opened in binary mode (even if the argument is bytes, it will convert to a text expression string and write and fail).
Python 3's print
is not a statement, but is a function.
© 2024 OneMinuteCode. All rights reserved.