Sign in to your Python Morsels account to save your screencast settings.
Don't have an account yet? Sign up here.
You can print to a file in Python.
print function writes to standard outputAccording to the documentation for Python's built-in print function, print accepts an optional file argument:
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
This file argument defaults to sys.stdout, which stands for standard output.
You can think of this standard output object as a writable file-like object.
So this sys.stdout object has a write method (just like a writable file object would):
>>> import sys
>>> z = sys.stdout.write("Hello!\n")
But when we call its write method, it won't write to a file.
Instead, it writes to the screen:
>>> z = sys.stdout.write("Hello!\n")
Hello!
This is what the print function does under the hood (by default): it calls the write method on sys.stdout.
>>> print("Hello!")
Hello!
Notice that we wrote a newline character (\n) at the end when we called the write method.
The print function prints a newline character at the end by default.
In fact, it also converts whatever we give to it to a string and puts spaces between them (if we give it multiple things):
>>> print(1, 2)
1 2
print functionThe print function is a higher-level way of looking at the world than writing to standard output manually.
We could embrace this higher-level abstraction and use it when writing to a file.
Let's say we're trying to make a file named numbers.txt that contains five randomly generated numbers.
We'll loop five times, and we'll call the randint function from Python's random module in each iteration of our loop:
>>> from random import randint
>>> with open("numbers.txt", mode="wt") as f:
... for _ in range(5):
... randint(0, 999)
But we're not going to call the write method on our file (not directly at least).
Instead, we'll print to our file object (not to the screen, to our file):
... print(randint(0, 999), file=f)
When we run this code, we don't see anything printed out.
>>> from random import randint
>>> with open("numbers.txt", mode="wt") as f:
... for _ in range(5):
... print(randint(0, 999), file=f)
...
>>>
But our file has changed!
Our numbers.txt file now contains five random numbers, each on their own line:
659
387
542
372
923
These numbers are each on their own line because print took each number we gave to it, converted it to a string, and added a newline character at the end.
The print function does all of that for us by default.
write method can only write text to a fileIf we had passed these numbers to the write method instead of using print, we would get an error::
>>> from random import randint
>>> with open("numbers.txt", mode="wt") as f:
... for _ in range(5):
... f.write(randint(0, 999))
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: write() argument must be str, not int
Because we can't write numbers to a file; we can only write strings to a text file. So we'd need to convert these numbers to strings.
... f.write(str(randint(0, 999)))
But we also want to add a newline character at the end.
So we should probably use an f-string and then put a newline character (\n) at the end:
>>> with open("numbers.txt", mode="wt") as f:
... for _ in range(5):
... f.write(f"{randint(0, 999)}\n")
...
4
4
4
4
4
This works. Our file has changed:
164
405
195
474
869
While this does work, it does the same thing that we were doing with print, but it took a little bit more effort.
I find this use of print a little bit easier to understand:
print(randint(0, 999), file=f)
That this use of the write method on our file:
f.write(f"{randint(0, 999)}\n")
If you're writing to a file line-by-line and you don't like putting a newline character at the end of each line and manually converting your objects to strings before writing, you might find it helpful to print to your file (instead of manually calling the write method on your file object).
We don't learn by reading or watching. We learn by doing. That means writing Python code.
Practice this topic by working on these related Python exercises.
Sign in to your Python Morsels account to track your progress.
Don't have an account yet? Sign up here.