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:
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 :
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.
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.