Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为什么我的代码不打印?_Python - Fatal编程技术网

Python:为什么我的代码不打印?

Python:为什么我的代码不打印?,python,Python,请参见最后四行: from sys import argv script, filename = argv print "we're going to erase %r." % filename txt = open(filename) print txt.read() print "If you do not want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print

请参见最后四行:

from sys import argv

script, filename = argv
print "we're going to erase %r." % filename

txt = open(filename)
print txt.read()
print "If you do not 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. Good 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 "I'm going to write these to the file."
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
target.close() #Need to close the file when done editing, or else cant open.

print "Here's the updated file!"
txt = open(filename)
print txt.read()
我试图在命令提示符下显示更新的文件,但它没有打印,打印的最后一行显示更新的文件!更新的文件在哪里


更新:我让它工作了,我忘了包括一行target=openfilename'w',我试图通过删除我的评论来让它看起来更容易,但是,我不小心删除了这个重要的peice。它现在也在打印我想要的东西。谢谢你的帮助,我不知道为什么它现在能工作。

无需关闭并重新打开该文件

target.write("%s\n%s\n%s\n" % (line1, line2, line3))
target.close() #Need to close the file when done editing, or else cant open.

print "Here's the updated file!"
txt = open(filename)
print txt.read()
您只需在“w+”模式下打开文件,然后就可以搜索位置0;文件的开头

target.write("%s\n%s\n%s\n" % (line1, line2, line3))
target.seek(0)

print "Here's the updated file!"    
print txt.read()

当您使用“w”或“w+”打开文件进行写入时,它将删除文件内容-没有理由截断它。

该脚本有问题。例如,目标分配到哪里?您没有发布正在运行的代码。如果您运行此代码,您将得到target的NameError,因为您没有定义任何名为target的变量。如果您发布收到的任何错误消息的文本,这也会有所帮助。如果它运行时没有错误消息,则表明该文件是空的-您是否手动打开该文件以确认那里有要打印的信息?更新:我让它工作了,我忘了包括一行target=openfilename,“w”,但是,我试图通过删除我的注释使它看起来更容易,我不小心删除了这个重要的文件。它现在也在打印我想要的东西。谢谢你的帮助,我不知道为什么它现在能工作。