December 2018
Beginner to intermediate
796 pages
19h 54m
English
Now that we know how to open a file, let's see a couple of different ways that we have to read and write to it:
# files/print_file.pywith open('print_example.txt', 'w') as fw: print('Hey I am printing into a file!!!', file=fw)
A first approach uses the print function, which you've seen plenty of times in the previous chapters. After obtaining a file object, this time specifying that we intend to write to it ("w"), we can tell the call to print to direct its effects on the file, instead of the default sys.stdout, which, when executed on a console, is mapped to it.
The previous code has the effect of creating the print_example.txt file if it doesn't exist, or truncate it in case it does, and writes the line Hey ...
Read now
Unlock full access