我是 Python 新手,但我有文本文件,如:
12345 | 6789 | abcd | efgh
我希望我的输出是这样的:
12345
6789
abcd
efgh
=====================
我真的不知道剧本 但是我用那些函数 split() , strip() 做了很多脚本,blame blame blame
但是我没有做到 所以我寻求帮助是有人可以。
我将不胜感激。
with open('contacts_index1.txt') as f:
lines = f.read().splitlines("|")
请您参考如下方法:
从您的所有评论来看,问题似乎与文件中的实际文本有关,而不是解析它的能力。看来这里大家的解决方案都是对的,你只需要强制编码即可。
您描述的错误描述为in this other StackOverflow post .
with open('contacts_index1.txt', 'r') as f:
lines = f.read().encode("utf-8").replace("|", "\n")
编辑:这个问题似乎是一个没有正确解码的令人讨厌的字符。使用 open,您可以告诉它忽略无法解码的字符。
import io
with io.open("contacts_index1.txt", errors="ignore") as f:
lines = f.read()replace("|", "\n")
