Zed shaw exercise 16 [duplicate] - python

This question already has answers here:
Behaviour of truncate() method in Python
(2 answers)
Closed 7 years ago.
I'm reading Zed Shaw's Python book, right now i'm trying to go further in exercise 16 by adjusting it a little:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'r+')
print "Displaying the file contents:"
print target.read()
print "Truncating the file. Goodbye!"
target.truncate()
print "Now i'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_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")
print "And finally, we close it."
target.close()
Note that i'm using 'r+' instead 'w' because i want to read and write in the exercise, but something is happening: target.truncate() doesn´t work, the information in the file persist. Why is the program proceeding in this way?
Thank you for your time.
P.S. I'm from Colombia, english isn't my native language, so please excuse my errors.

truncate defaults to truncating the file at the current position, which after a read call will be at the end of the file. If you want to clear the entire file, use truncate(0).

Related

after writing to a file, .read() is printing strange results

I'm learning Python as a first language, my study book says to add code that reads the newly written file, however whenever I try a print target.read() the script runs but when it is supposed to output on the 4th line from last, it outputs strange unreadable characters.
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you wish to cancel, press CTRL-C."
print "To continue, press RETURN."
raw_input(">")
print "Opening the file..."
target = open(filename, 'w+')
print "Truncating the file. Bye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
print "These will be wrote to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "The text in this file reads as: \n "
print target.read()
print "And finally, we close it."
target.close
read() starts reading from the current position in the file. After all the write() calls, the current position is after the last byte that was written. You need to go back to the beginning of the file to read what you just wrote:
target.seek(0)
print "The texxt in this file reads as: \n"
print target.read()
BTW, you don't need to use target.truncate(). When you open a file in w or w+ mode, it's automatically truncated.
And target.close doesn't do anything. You need parentheses to call the function, so it should be target.close(). But it would be better style to use with so the file is closed automatically.
Close the file & open it for reading before, uh, reading from it.
Change print target.read()`with
with open("example_txt.txt") as xx:
print xx.read()
target.close ---> target.close()
A few things:
As stated earlier, the w+ already starts at the beginning of the file, so your truncate() is unnecessary. Also, you aren't reading the whole file object when you do the read() since the target is on the last line which is just an /n character. If you open the txt file after, you will see your three lines and an empty line at the end from your last /n you wrote.
Typically I would think it's better practice to either build your file you want to write in memory and write the entire thing so you can check it before writing. Otherwise write incrementally, close it and re-open it for reading.
Lastly you should use the following syntax for opening files so they automatically close:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you wish to cancel, press CTRL-C."
print "To continue, press RETURN."
raw_input(">")
print "Now I'm going to ask you for three lines."
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
print "Opening the file..."
with open(filename, 'w+') as f:
print "These will be written to the file."
f.write(line1 + '\n')
f.write(line2 + '\n')
f.write(line3 + '\n')
print "The file will close automatically after this line."
print "The text in this file reads as: \n "
with open(filename, 'r') as f:
print f.read()
There are many other ways to do this even simpler, but this is a good alternative. If you follow along, you'll see we build our text for input, then we write each line while the file is open and it automatically closes after it leaves the 'with' block. Then we can open it safely read-only for printing the contents. We could have also appended your lines together into a single variable, printed it before writing anything to make sure it's right, and then write the entire object as one piece.
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you wish to cancel, press CTRL-C."
print "To continue, press RETURN."
raw_input(">")
print "Now I'm going to ask you for three lines."
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
contents = line1 + '\n' + line2 + '\n' + line3 + '\n'
print "These will be written to the file.\n"
print contents
print "Opening the file..."
with open(filename, 'w+') as f:
f.write(contents)
print "The file will close automatically after this line."

Append and Truncating together in Python

So, I am at exercise 16 of Zed Shaw's Python book.
I thought of trying out both append and truncate on the same file. I know, this does not make sense. But, I am new and I am trying to learn what would happen if I used both.
So, first I am opening the file in append mode and then truncating it and then writing into it.
But, the truncate is not working here and whatever I write gets appended to the file.
So, can someone kindly explain why the truncate would not work ? Even though I am opening the file in append mode first, I believe I am calling the truncate function after that and it should have worked !!!
Following is my code:
from sys import argv
script, filename = argv
print "We're going to erase %r." %filename
print "If you don't want that. hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'a')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write(line1 + "\n" + line2 + "\n" + line3)
print "And finally, we close it."
target.close()
Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position.
When you open your file with 'a' mode, the position is at the end of the file.
You can do something like this
f = open('myfile', 'a')
f.tell() # Show the position of the cursor
# As you can see, the position is at the end
f.seek(0, 0) # Put the position at the begining
f.truncate() # It works !!
f.close()
The argument 'a' opens the file for appending. You will need to use 'w' instead.

new python user..printing txt file with .read, not working

I'm reading How to Learn Python the Hard Way by Zed Shaw and I can't get this part right. I'm trying to rewrite the contents of a txt file and then print it, my last line wont work(nothing shows up after I print "I'm going to write these to the file."), it seems like it works until I add the .read command...
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that hit CTRL-C (^C)."
print "If you do want that, hit RETURN"
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_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")
print open(filename).read()
You need to call target.close() or target.flush() so that the newly written content would be available for .read().
from reviewing the website that you got this code from you didnt properly complete typing in the last 2 lines that zed shaw had typed from http://learnpythonthehardway.org/book/ex16.html:
print "And finally, we close it."
target.close()

Cannot read file after writing to it

I am currently reading "Learn Python the hard way" and have reached chapter 16. I can't seem to print the contents of the file after writing to it. It simply prints nothing.
from sys import argv
script, filename = argv print "We are going to erase the contents of %s" % filename print "If you don\'t want that to happen press Ctrl-C"
print "If you want to continue press enter"
raw_input("?") print "Opening the file..." target = open(filename, "w")
print "Truncating the file..." target.truncate()
print "Now i am going to ask you for 3 lines"
line_1 = raw_input("Line 1: ")
line_2 = raw_input("Line 2: ")
line_3 = raw_input("Line 3: ")
final_write = line_1 + "\n" + line_2 + "\n" + line_3
print "Now I am going to write the lines to %s" % filename
target.write(final_write)
target.close
print "This is what %s look like now" %filename
txt = open(filename)
x = txt.read() # problem happens here
print x
print "Now closing file"
txt.close
You're not calling functions target.close and txt.close, instead you're simply getting their pointers. Since they are functions (or methods, to be more accurate) you need () after the function's name to call it: file.close().
That's the problem; you open the file in write mode which deletes all the content of the file. You write in the file but you never close it, so the changes are never committed and the file stays empty. Next you open it in read mode and simply read the empty file.
To commit the changes manually, use file.flush(). Or simply close the file and it will be flushed automatically.
Also, calling target.truncate() is useless, since it's already done automatically when opening in write mode, as mentioned in the comments.
Edit: Also mentioned in the comments, using with statement is quite powerful and you should use it instead. You can read more of with from http://www.python.org/dev/peps/pep-0343/, but basically when used with files, it opens the file and automatically closes it once you unindent. This way you don't have to worry about closing the file, and it looks much better when you can clearly see where the file is being used, thanks to the indentation.
Quick example:
f = open("test.txt", "r")
s = f.read()
f.close()
Can be done shorter and better looking by using with statement:
with open("test.txt", "r") as f:
s = f.read()

getting output with weird text like☻

Hey! I am getting a problem with my script.
I wrote it when reading LPTHW book.
I am not getting an error message but I am not getting the correct output, I think there might be a setting wrong with my system. I am confused.
Here is the script:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w+')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1= raw_input("line1: ")
line2= raw_input("line2: ")
line3= raw_input("line3: ")
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")
print "Now, I am going to read the file"
print target.read()
print "And finally, we close it."
target.close()
and here is the output:
PS C:\Users\Isaac\lpthw> python ex1.py sample.txt
We're going to erase 'sample.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line1: i
line2: love
line3: mo
I'm going to write these to the file.
Now, I am going to read the file
#☻ ` ▬☻ ` ▬☻ .☻
When you call target.write(), the file pointer is left just after the written data. You can call target.tell() to see where it is:
>>> target.tell()
0
>>> target.write('hello')
>>> target.tell()
5
You need to seek to the beginning of the file before you read it:
target.seek(0)
print target.read()

Categories

Resources