我从 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 行:三个 第 2 行:两个 第 3 行:一个 将行写入文件 以下是 ex16_text.txt 文件的内容:
最佳答案
你应该 flush写入文件以确保字节已写入。另请阅读警告:
Note: flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.
如果您已完成对文件的写入并想以只读访问权限再次打开它,您也应该关闭该文件。请注意,关闭文件也会刷新 - 如果关闭文件,则不需要先刷新。
在 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()
关于Python 基础 - 为什么我的文件内容不打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4160444/