In this lesson, you will learn more another basic operation — writing.
How to write to files
Let's open a file for writing, write some text, and then close it. The write
method writes a string to the file without any additional processing:
f = open("foo.txt", "w")
f.write('Hello\nWorld!') # 12
f.close()
Here "w"
signifies the write mode, and 12
indicates the number of characters we wrote to the file using the write
call. Now, let's open the file in read mode and read the entire contents:
f = open("foo.txt", "r") # The `r` stands for reading mode
f.read() # 'Hello\nWorld!'
f.close()
Hurray! We have read what we previously wrote.
How to work with positions of files
The write
method can be called multiple times. We will get the number of characters written as an output each time. The text will accumulate because each write
call moves the so-called current file position to the end of the file.
The read
also considers the current situation: it reads the text from the current position to the end of the file. You can explicitly specify how many characters to read. In this case, the method will try to read the number of characters if the file has enough. In any case, calling the read
method moves the position to where the reading ended.
When we open a file, the current position always points to the first character of the text, like position zero. When you read the file to the end using the read
method without parameters, the position moves to the end of the file, and subsequent reads yield nothing:
f = open("foo.txt", "r") # The `r` stands for reading mode
f.read() # 'Hello\nWorld!'
f.read() # ''
f.close()
We can also change the file position manually. For this purpose, we use the seek
method, which you can read about in the documentation.
Most often, you will work with text files. The position is not as important in such files since it doesn't consider line breaks in the text. However, manipulating position and offset becomes critical when working with binary files. I recommend experimenting with file positioning and reading/writing non-text data.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.