r+

We discussed reading and writing to files using the r and w flags. There is another called r+. This flag enables reading and writing to a file. Let's review an example that enables us to understand this flag.

Let's review the contents of write_file.txt once again:

    I am excited to learn Python using Raspberry Pi Zero
This is a line appended to the file

Let's modify the second line to read: This is a line that was modified. The code sample is available for download along with this chapter as seek_to_write.py.

if __name__ == "__main__": 
# open text file to read and write
file = open('write_file.txt', 'r+')

# set the pointer to the desired position
file.seek(68)
file.write('that was modified ')

# rewind the pointer to the beginning of the file
file.seek(0)
data = file.read()
print(data)
file.close()

Let's review how this example works:

  1. The first step in this example is opening the file using the r+ flag. This enables reading and writing to the file.
  2. The next step is moving to the 68th byte of the file
  3. The that was modified string is written to the file at this position. The spaces at the end of the string are used to overwrite the original content of the second sentence.
  4. Now, the file pointer is set to the beginning of the file and its contents are read.
  5. When the preceding code snippet is executed, the modified file contents are printed to the screen as follows:
       I am excited to learn Python using Raspberry Pi Zero
This is a line that was modified

There is another a+ flag that enables appending data to the end of the file and reading at the same time. We will leave this to the reader to figure out using the examples discussed so far.

We have discussed different examples on reading and writing to files in Python. It can be overwhelming without sufficient experience in programming. We strongly recommend working through the different code samples provided in this chapter
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.239.123