Python文本文件中奇怪的换行符

标签 python string utf

我有另一个程序(我没有源代码)写入文本文件,然后当我尝试像这样读取文本文件时,

with open("domain.com/alive_domains.txt") as f:
    for line in f:
        print(line)

输出是这样的:(这是直接从 pycharm 的控制台窗口复制并粘贴的)

http://stage.oidc.payments.domain.com

https://oidc.help.domain.com

https://search.domain.com

https://oidc.payments.domain.com

https://stage.oidc.payments.domain.com

http://stage.oidc.help.domain.com

https://stage.oidc.help.domain.com

由于某种原因,有一些奇怪的新行字符,我认为它们不是新行

我尝试通过执行类似的操作来解决此问题

<小时/>
abc = "abcdefghijklmnopqrstuvwxyz:/."

def fix_string(s):
    new_s = ""
    for char in s:
        if char in abc:
            new_s += char
    return ''.join(new_s)

with open("domain.com/alive_domains.txt") as f:
    for line in f:
        print(fix_string(line))

我得到了相同的输出..

<小时/>

我尝试谷歌搜索,发现了这个正则表达式

   with open("domain.com/alive_domains.txt") as f:
        for line in f:
            line = re.sub("[^a-z0-9/.:]+","", line, flags=re.IGNORECASE)
            print(fix_string(line))

再次,它为我提供了与新行相同的输出

它不会对我尝试逐行读取的任何其他文件执行此操作。有没有办法识别奇怪的字符?如果有的话

最佳答案

从输入文件中读取的每一行都是一个已以换行符结尾的字符串。当您将这些字符串写入输出文件时,print在输出中添加另一个换行符,从而产生双换行符。

要抑制此行为,请编写

print(some_string, end='')

或者,如果您不需要print的附加功能,您可以通过直接写入文件句柄

f.write(some_sring)

关于Python文本文件中奇怪的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60133178/

相关文章:

python - 如何使用 pip 将 Python 包安装到我的 Divio Docker 项目中?

python - 如何并排绘制 2 个 seaborn lmplots?

c# - 字符串转换 C#

python - 为什么 sys.getdefaultencoding() 与 sys.stdout.encoding 不同?这如何破坏 Unicode 字符串?

c# - Git 无法区分或 merge utf-16 编码的 .cs 文件

python - 在 python 中将字符转换为对应的 ascii 字符的最简单方法是什么?

c - C-如何解析反斜杠字符

Ruby 多字符串替换

javascript - 检查文件/blob 对象是否有效 UTF-8

Python PyQt5 - QEvent Keypress 执行两次