在python中为什么它不会没有换行打印

我是学习
python的新手.我不明白为什么print命令会在屏幕上输出所有变量,但是写入命令只能写入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()

最佳答案 操作系统通常在换行后刷新写缓冲区.

当您打开(文件名,’a’)文件时,默认情况下会应用这些相同的规则.

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

The optional buffering argument specifies the file’s desired buffer
size: 0 means unbuffered, 1 means line buffered, any other positive
value means use a buffer of (approximately) that size (in bytes). A
negative buffering means to use the system default, which is usually
line buffered
for tty devices and fully buffered for other files. If
omitted, the system default is used.

调用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)
点赞