【问题标题】:In python why it won't print without newline在python中为什么没有换行符就不会打印
【发布时间】:2016-11-02 21:19:50
【问题描述】:

我是学习 python 的新手。我不明白为什么 print 命令会在屏幕上输出所有变量,但 write command to file 只写入 2 个前两个变量。

print "Opening the file..."
target = open(filename, 'a+')

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
line4 = line1 + "\n" + line2 + "\n" + line3

# This command prints all 3 (line1,line2,line3) variables on terminal
print line4

#This command only writes line1 and line2 variables in file
target.write(line4)

print "close the file"
target.close()

【问题讨论】:

    标签: python


    【解决方案1】:

    操作系统通常在换行后刷新写入缓冲区。 当您open(filename, 'a+') 文件时,这些规则默认适用。

    来自文档:https://docs.python.org/2/library/functions.html#open

    可选的缓冲参数指定文件所需的缓冲区 size: 0 表示无缓冲,1 表示行缓冲,任何其他正数 value 表示使用(大约)该大小(以字节为单位)的缓冲区。一个 负缓冲意味着使用系统默认值,通常是 为 tty 设备行缓冲,为其他文件完全缓冲。如果 省略,使用系统默认值。

    致电target.close() 以确保将所有内容都写出(“刷新”)到文件中(根据下面的评论,为您关闭刷新)。您可以使用target.flush() 手动刷新。

    print "Opening the file..."
    target = open(filename, 'a+')
    
    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")
    line4 = line1 + "\n" + line2 + "\n" + line3
    
    # This command prints all 3 (line1,line2,line3) variables on terminal
    print line4
    
    target.write(line4)
    
    target.close() #flushes
    

    或者,使用with 关键字将在我们离开with 块时自动关闭文件:(请参阅What is the python keyword "with" used for?

    print "Opening the file..."
    with open(filename, 'a+') as target:
    
       line1 = raw_input("line 1: ")
       line2 = raw_input("line 2: ")
       line3 = raw_input("line 3: ")
       line4 = line1 + "\n" + line2 + "\n" + line3
    
       # This command prints all 3 (line1,line2,line3) variables on terminal
       print line4
    
       target.write(line4)
    

    【讨论】:

    • close 自动刷新,因此您通常不需要自己flush
    • 我认为你应该添加关于with的评论
    • 忘了提到我已经在最后包含了 close 但它仍然只将 line1 和 line2 变量打印到文件中。尝试了with open(filename, 'a+') as target:,但结果相同。谁能用外行解释一下。
    • 您是否在检查文件前等待了几秒钟?写入/关闭后,您保证操作系统有完整的数据写入磁盘,但它可能实际上不会在几秒钟内将其写入。
    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多