我有另一个程序,(我没有源代码)写入文本文件,然后当我尝试像这样读取文本文件时,
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))
而且我得到了相同的输出。
我尝试使用Google搜索,并遇到了此正则表达式
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
或者,如果您不需要print(some_string, end='')
的附加功能,则可以通过以下方式直接写入文件句柄:>
print