Feb-18-2018, 03:00 AM
Not a big fan (or even a small fan) of this book
This is very ugly code, and I have no idea why the
author is teaching this way.
The proper way to open a file and process data is:
with open(filename, mode) as fp:
# do reads, writes, etc here
When you come out of this loop, the file is closed for you, you do not have to issue a close statement.
your question:
r+ opens for reading and writing (cannot truncate a file)
That is correct, but in the example, and this should have been explained, the file pointer on
open is at the start of file, so when you write, you are overwriting whatever is at that location.
in order to append to a file in this mode, you must seek end of file first
the instruction to do that is seek, used as follows ( in this awful code example)
This is very ugly code, and I have no idea why the
author is teaching this way.
The proper way to open a file and process data is:
with open(filename, mode) as fp:
# do reads, writes, etc here
When you come out of this loop, the file is closed for you, you do not have to issue a close statement.
your question:
Quote:From what we read in the pydocs of python 3.6, "r+" mode isn't supposed to truncate the file.
r+ opens for reading and writing (cannot truncate a file)
That is correct, but in the example, and this should have been explained, the file pointer on
open is at the start of file, so when you write, you are overwriting whatever is at that location.
in order to append to a file in this mode, you must seek end of file first
the instruction to do that is seek, used as follows ( in this awful code example)
import io from sys import argv script, filename = argv print("We're going to erase", filename, ".") print("If you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN") input("?") print("Opening the file...") target = open(filename, 'w') # W DOES TRUNCATE (=ERASE) THE PREVIOUS CONTENT OF THE FILE print('target: {}'.format(target)) print("Truncating the file. Goodbye!") # target.truncate() print("Now I'm going to ask you for three lines.") line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") print("I'm going to write these to the file.") target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") target.close() target = open(filename, "r+") target.seek(0, io.SEEK_END) target.write(f"{line1}\n\t{line2}\n\t{line3}") new = "{} {} {}" print(new.format(line1, line2, line3)) target.close()which results in:
Output:λ python MultipleOpen.py goober.txt
We're going to erase goober.txt .
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN
?
Opening the file...
target: <_io.TextIOWrapper name='goober.txt' mode='w' encoding='cp1252'>
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: line1
line 2: line2
line 3: line3
I'm going to write these to the file.
line1 line2 line3
λ cat goober.txt
line1
line2
line3
line1
line2
line3