繁体   English   中英

为python写输出不起作用

[英]writing output for python not functioning

我正在尝试输出一个新的txt文件,但出现空白。 我正在做这个

my_file = open("something.txt","w")
#and then
my_file.write("hello")

在此行之后,它只说5,然后文件中没有文本

我究竟做错了什么?

您必须在刷新写入之前关闭文件 如果我打开翻译,然后输入:

my_file = open('something.txt', 'w')
my_file.write('hello')

然后在文本程序中打开文件,没有文本。

如果再发出:

my_file.close()

瞧! 文本!

如果您只想刷新一次并继续写入,也可以这样做:

my_file.flush()
my_file.write('\nhello again')  # file still says 'hello'
my_file.flush()   # now it says 'hello again' on the next line

顺便说一句,如果您碰巧读了 file.write 精美文档 ,它只有两行,那么您将得到答案(强调我的意思):

将字符串写入文件。 没有返回值。 由于存在缓冲,在调用flush()或close()方法之前,字符串实际上可能不会显示在文件中。

如果您不想关闭文件,请with使用:

with open("something.txt","w") as f: 
    f.write('hello')

然后python会自动为您关闭文件。

正如两位炼金术士指出的,该文件必须关闭。 python文件编写器使用缓冲区(我认为是BufferedIOBase ),这意味着在将它们批量写入磁盘之前,它会收集一定数量的字节。 这样做是为了在单个文件上执行大量写操作时节省开销。

另外:处理文件时,请尝试使用with -environment的文件,以确保在完成写入/读取后关闭文件:

with open("somefile.txt", "w") as myfile:
    myfile.write("42")

# when you reach this point, i.e. leave the with-environment,
# the file is closed automatically.

python文件编写器使用缓冲区(我认为是BufferedIOBase),这意味着在将它们批量写入磁盘之前,它会收集一定数量的字节。 这样做是为了在单个文件上执行大量写操作时节省开销。 引用@ m00am

您的代码也没问题。 只需添加一个用于关闭文件的语句,然后即可正常工作。

my_file = open("fin.txt","w")
#and then
my_file.write("hello")
my_file.close()

暂无
暂无

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

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