Python 在变量后插入一个回车符 return 和一个换行符,而不仅仅是换行符

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 会在末尾插入一个回车符 Return 和一个换行符(例如 AAAA CR LF),而使用 \r 只会插入一个运输 Return(例如 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()

这应该可以解决您的问题。