Working with File Contents
Now that we know how to read and write files, let's look at some more advanced examples of working with file contents.
Reading a file line by line
Sometimes, we may want to read a file line by line, rather than reading the entire contents at once. To do this, we can use the readline
method of the file object.
Here is an example of how to read a file line by line:
## Open the file
f = open('filename.txt', 'r')
## Read and print each line
for line in f:
print(line)
## Close the file
f.close()
The for
loop iterates over the lines of the file. On each iteration, it reads and prints the current line. When there are no more lines to read, the loop ends and the file is closed.
Writing to a file line by line
To write to a file line by line, we can use the writelines
method of the file object. This method takes a list of strings as an argument and writes them to the file, with each string in the list becoming a separate line in the file.
Here is an example of how to write to a file line by line:
## Open the file
f = open('filename.txt', 'w')
## Write a list of lines to the file
lines = ['Line 1', 'Line 2', 'Line 3']
f.writelines(lines)
## Close the file
f.close()
Appending to a file
To append to a file, rather than overwriting it, we can use the 'a'
mode when opening the file. This will open the file in append mode, allowing us to add new content to the end of the file without overwriting the existing content.
Here is an example of how to append to a file:
## Open the file
f = open('filename.txt', 'a')
## Append some text to the file
f.write('This is new content')
## Close the file
f.close()