Python Forum
Question about Open Fonction
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about Open Fonction
#1
Hi,
i am currently learning Python 3 with a friend, and we are using "Learn Python 3 the Hard Way" books from Zed Shaw. We are at the moment at the exercice 16 and we are testing things from what we learned. Here is the code:
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("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.write(f"{line1}\n\t{line2}\n\t{line3}")


new = "{} {} {}"

print(new.format(line1, line2, line3))

target.close()
The question is about the second open. From what we read in the pydocs of python 3.6, "r+" mode isn't supposed to truncate the file.

But while runing this code with python 3.6 and setting line1 to "a", line2 to "b", line3 to "c" and filename to "ex16.txt", from what we understood, we are supposed to get this in ex16.txt :
Output:
a b ca b c
But what we get is :
Output:
a b c
Did we understood something wrong? Is it a "bug"? We are a little puzzled by this result, so if anyone is able to answer us, we would greatly appreciate.

Ok, nevermind my post, after some try and retry, we found where we were wrong.

The "r+" mode doesn't truncate the file, but it put the pointer at the 0 position, hence rewritting what we got with the first open.

Sorry for this "useless" post and thank you if you took the time to read me.
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Quiver fonction Blaue_Blume04 2 2,440 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