我是学习python的新手。我不明白为什么print命令会在屏幕上输出所有变量,但写命令到文件只会写出前两个变量。
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()
答案 0 :(得分:7)
操作系统通常在换行后刷新写缓冲区。
当您open(filename, 'a+')
文件时,默认情况下会应用这些相同的规则。
来自文档:https://docs.python.org/2/library/functions.html#open
可选的buffering参数指定文件所需的缓冲区 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)