繁体   English   中英

Python基础知识 - 为什么不是我的文件打印的内容?

[英]Python basics- why aren't the contents of my file printing?

我是从eclipse运行的,我正在使用的文件名是ex16_text.txt(是的我输入正确。它正确地写入文件(输入出现),但是“print txt.read()”似乎没有做任何事情(打印一个空行),看到代码后的输出:

filename = raw_input("What's the file name we'll be working with?")

print "we're going to erase %s" % filename

print "opening the file"
target = open(filename, 'w')

print "erasing the file"
target.truncate()

print "give me 3 lines to replace file contents:"

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "writing lines to file"

target.write(line1+"\n")
target.write(line2+"\n")
target.write(line3)

#file read
txt = open(filename)

print "here are the contents of the %s file:" % filename
print txt.read()

target.close()

输出:

我们将使用的文件名是什么?ex16_text.txt我们要擦除ex16_text.txt打开文件擦除文件给我3行替换文件内容:第1行:第3行:第2行:第3行:在这里写行文件是ex16_text.txt文件的内容:

您应该在写入文件后刷新文件以确保已写入字节。 另请阅读警告:

注意:flush()不一定将文件的数据写入磁盘。 使用flush()后跟os.fsync()来确保此行为。

如果您已完成写入并希望以只读访问权限再次打开该文件,则还应关闭该文件。 请注意,关闭文件也会刷新 - 如果关闭它,则不需要先刷新。

在Python 2.6或更高版本中,您可以使用with语句自动关闭文件:

with open(filename, 'w') as target:
    target.write('foo')
    # etc...

# The file is closed when the control flow leaves the "with" block

with open(filename, 'r') as txt:
    print txt.read()
target.write(line2+"\n")
target.write(line3)
target.close() #<------- You need to close the file when you're done writing.
#file read
txt = open(filename)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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