简体   繁体   中英

Python reading file but the command line prints a blank line

I am doing Learn Python the Hard Way and am on exercise 16. The study drill says to write a script using read and argv .

My code is as follows:

from sys import argv

script, file_name, pet_name = argv

print "Ah, your pet's name is %r." %pet_name
print "This will write your pet's name in a text file."
print "First, this will delete the file. "
print "Proceeding..."

writefile = open(file_name, 'w')
writefile.truncate()
writefile.write(pet_name)
writefile.close

raw_input("Now it will read. Press ENTER to continue.")

readfile = open(file_name, "r")
print readfile.read()

The code works until the end. When it says to print the file, the command line gives a blank line.

PS C:\Users\[redacted]\lpthw> python ex16study.py pet.txt jumpy
Ah, your pet's name is 'jumpy'.
This will write your pet's name in a text file.
First, this will delete the file.
Proceeding...
Now it will read. Press ENTER to continue.

PS C:\Users\[redacted]\lpthw>

I am not sure why the script is just printing a blank file.

You never called the writefile.close() method:

writefile.write(pet_name)
writefile.close
#              ^^

Without closing the file, the memory buffer to help speed writing never gets flushed and the file effectively remains empty.

Either call the method:

writefile.write(pet_name)
writefile.close()

or use the file as a context manager (with the with statement ) to have Python close it for you:

with open(file_name, 'w') as writefile:
    writefile.write(pet_name)

Note that the writefile.truncate() call is entirely redundant. Opening a file in write mode ( 'w' ) always truncates the file already .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM