加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:55:36 所属栏目: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
我是学习 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,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,line3) variables on terminal
   print line4

   target.write(line4)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读