Python Forum
Question about Open Fonction
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about Open Fonction
#2
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:
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
Reply


Messages In This Thread
Question about Open Fonction - by ginjou - Feb-18-2018, 02:02 AM
RE: Question about Open Fonction - by Larz60+ - Feb-18-2018, 03:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Quiver fonction Blaue_Blume04 2 2,482 Mar-21-2019, 03:05 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020