我正在通过“学习python艰难的方式”一书,我遇到Second Exercise of the 16th study drill.中的问题我使用的是最新版本的python 3.
到目前为止,我写的代码看起来像这样:
from sys import argv
script, filename = argv #we input the filename into argv
print ("We're going to erase %r." % filename) #tells us the name of the file we're deleting
print ("If you don't want that, hit CTRL-C (^C)")
print ("If you do want that, hit RETURN.")
input("?") #look into error unexpected EOF while parsing, I had to type "", if I don't program ends here
print ("Opening the file...")
target = open(filename, "w") #opens the file
print ("Truncating the file. Goodbye!")
target.truncate() #erases everything in the file
print ("Now I'm going to ask you for three lines")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
#summary: we create 3 input variables we'll use under here
print ("I'm going to write these to the file.")
target.write(line1) #summary: we write in the terminal what we want in our file and use that
target.write("\n") #we also have this newline command after every line to make sure it's not all in one line
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#The default code is done at this point
print ("Type the filename again and I'll read it back to you or press CTRL + C (^C) to exit")
file_again = input(">")
print (file_again) #Added to try to see what this gave me, it gives nothing back --- isn't working, why?
print ("Now I'll read the file back to you!") #This prints
text_again = open(file_again) #Not sure if this is working
print (text_again.read()) #Is doing nothing in the Terminal
print("And finally we close the file") #Works
target.close()
此时我想知道为什么“#默认代码在此时完成”之后的东西不能正常工作,我从另一个程序中完全按原样撕掉它(同一本书的练习15),我的命令行看起来像这样:
C:\PATH\Study Drills>py SD8.py "test.txt"
We're going to erase 'test.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
line 1: "Hey"
line 2: "yo"
line 3: "sup"
I'm going to write these to the file.
Type the filename again and I'll read it back to you or press CTRL + C (^C) to exit
>"test.txt"
Now I'll read the file back to you!
奖金问题:在我说的那句话中(“解析错误意外的EOF时,我必须输入”“,如果我不在此处编程结束”)为什么我必须加上引号?如果我不这样做,程序将以评论中提到的错误消息结束。
答案 0 :(得分:3)
完成所有write
次来电,close()
该文件后。由于操作系统缓冲等问题,在关闭文件对象之前,数据不能保证实际写入文件(退出程序时会自动完成,正如您可能已经注意到的那样 - 杀死程序并且数据将会在文件中。)
此外,您的truncate
电话是不必要的 - 以"w"
模式打开文件会立即将其截断。