An awesome thing about Python is how easy everything is. That also includes when it comes to reading and writing files.
This part of the tutorial will get you started with that.
- Step 1: A read a file and print the content. See how easy it is done.
- Lesson: First open the file. Read the content with readlines.
- Step 2: Modify the content of file content.txt to see how it affects the output of the program.
- Step 3: As you see, the line looping over the lines includes a new-line and the print function also includes one. A way to handle that could be as follows, where you also see another way to open a file.
- With the syntax of f = open(…) you need to remember to f.close() after you used the file.
- f.read() reads the full content of the file.
- content.splitlines() splits the content into lines without the new-line at the end.
- Step 4: Add a line number in front of each line. It should print:
0 This is awesome. 1 Python is awesome. 2 You are awesome.
- Step 5: See the example below and inspect how a file can be written.
- To write a file you need to set the ‘w’ in open(‘output.txt’, ‘w’) to indicate that you want to write the file.
- Step 6: Try to change the output file name to ‘my_output_file.txt’.
- Write the content from input.txt to output.txt with line numbers.