我正在学习Python作为第一语言,我的学习书说要添加读取新编写文件的代码,但是每当我尝试print target.read()
脚本运行但是应该在4日输出时从最后一行开始,它输出奇怪的不可读字符。
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
答案 0 :(得分:1)
read()
开始从文件中的当前位置读取。在所有write()
次调用之后,当前位置在写入的最后一个字节之后。你需要回到文件的开头来阅读你刚写的内容:
target.seek(0)
print "The texxt in this file reads as: \n"
print target.read()
顺便说一下,你不需要使用target.truncate()
。当您以w
或w+
模式打开文件时,它会自动截断。
并且target.close
没有做任何事情。您需要括号来调用该函数,因此它应该是target.close()
。但是使用with
会更好的风格,因此文件会自动关闭。
答案 1 :(得分:0)
关闭文件&打开它阅读之前,呃,从中读取。
答案 2 :(得分:0)
使用
更改print target.read()`with open("example_txt.txt") as xx:
print xx.read()
target.close ---> target.close()
答案 3 :(得分:0)
一些事情:
如前所述,w +已经从文件的开头开始,所以你的truncate()是不必要的。此外,当您执行read()时,您不会读取整个文件对象,因为目标位于最后一行,它只是一个/ n字符。如果你之后打开txt文件,你会看到你的三行和你写的上一个/ n末尾的空行。
通常情况下,我认为构建您想要在内存中写入的文件并编写整个文件以便在编写之前进行检查是更好的做法。否则逐渐写入,关闭它并重新打开它以供阅读。
最后,您应该使用以下语法打开文件,以便它们自动关闭:
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()
还有很多其他方法可以做到这一点更简单,但这是一个很好的选择。如果你继续,你会看到我们构建我们的文本作为输入,然后我们在文件打开时写下每一行,并在它离开'后自动关闭。块。然后我们可以安全地打开它,只读打印内容。我们也可以将你的线条一起添加到一个变量中,在写任何东西之前打印它以确保它是正确的,然后将整个对象写成一个整体。
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."