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

3 投票
2 回答
2692 浏览
提问于 2025-04-16 06:56

我在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行来替换文件内容: 第一行:three 第二行:two 第三行:one 正在写入文件内容 这是ex16_text.txt文件的内容:

2 个回答

6

在你写完文件后,应该刷新一下文件,这样才能确保你写入的数据真的被保存了。还有一点需要注意:

注意: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()
4

这段代码是用来处理某些特定功能的。它可能包含了一些逻辑,用于实现程序的某个部分。具体来说,代码块的内容可能涉及到变量的定义、条件判断、循环等基本编程概念。

如果你是编程小白,可以把它想象成一个食谱,里面列出了做某道菜所需的材料和步骤。每一行代码就像是一个步骤,告诉计算机该怎么做。

总之,这段代码的目的是为了让计算机按照预定的方式运行,完成特定的任务。

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)

撰写回答