[英]Python inserts both a carriage return and a line feed after variable, instead of just line feed
我创建了一个python脚本,用于从AAAA-ZZZZ等输出每1-4个字符的字母组合。
它运行完美,但是我只需要在打印变量的末尾插入换行符,因为我将其用作要在另一个脚本中使用的单词列表。
我尝试同时使用\\ r和\\ n,但是使用\\ n会同时插入回车符和换行符(例如AAAA CR LF),使用\\ r只会插入回车符(例如AAAA CR)。
我的问题是,是否可以在末尾仅插入换行符,还是由于python的限制而不可能? 我试过使用记事本手动替换每个字符,并且此方法有效,但是,这只是在修补问题,无法使用。
非常感谢您的帮助!
import string
alpha = string.ascii_uppercase
w=(a+b+c+d for a in alpha for b in alpha for c in alpha for d in alpha)
x=(a+b+c for a in alpha for b in alpha for c in alpha)
y=(a+b for a in alpha for b in alpha)
z=(a for a in alpha )
with open("Output.txt", "w") as text_file:
for i in [w, x, y, z]:
for k in i:
print("{}\r".format(k), file=text_file, end='')
这里的问题是线
print("{}\r".format(k), file=text_file, end='')
对于以文本模式(默认)打开的文件,python将/ n解释为等效于os.linesep,在Windows上为[CR] [LF],反之亦然。
import os
print(os.linesep)
查看http://docs.python.org/library/os.html
为防止这种情况,请以二进制模式打开文件。
with open("Output.txt", "wb") as my_file:
这告诉Python将文件视为纯字节序列,并且您会发现\\ n被视为单个换行符。
尝试:
with open("Output.txt", "bw") as text_file:
在Python3中,print()基本上在每次执行时都会添加新行。 为此,建议您使用sys模块的write函数。 制作下载栏时,我也遇到同样的问题。
码-
import sys
sys.stdout.write('\r')
sys.stdout.flush()
这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.