在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
调用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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |