我目前正在进行艰难学习 Python 中的练习 16,我的代码在写入文件时遇到问题,但我的最终打印命令不打印内容将文件拖到控制台上。在我的命令行上,它只是出现了几行空格。据我了解,“r+”以读写模式打开它,但计算机无法读取它。 有人可以告诉我有什么问题吗?任何帮助将不胜感激:)
from sys import argv
script, file = argv
print "The name of the file is %s" % file
filename = open(file,"r+")
print "First we must write something in it "
print "Do you want to continue?Press CTRL-C if not."
raw_input()
print "Type the first line of the text"
line1 = raw_input(">")+"\n"
print "Type the second line of text"
line2 = raw_input(">")+"\n"
print "Type the third line of text"
line3 = raw_input(">")+"\n"
sum_line = line1 + line2 + line3
print "Now I will write it to the file"
filename.write(sum_line)
print "The file now says:"
#This line here does not print the contents of the file
print filename.read()
filename.close()
最佳答案
正如第一个答案中所包含的那样,写入后偏移量将指向文件末尾。但是,您不需要关闭该文件并重新打开它。最好在阅读之前执行此操作:
filename.seek(0)
这将重置文件开头的偏移量。
然后简单地阅读它。
filename.read()
关于python - 在同一脚本中读取和写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839717/