主要问题是换行符(“\n”)出现在每行末尾,但最后一行除外。你可以结合使用
set
,
map
和
join
功能如下:
f = open('a.txt', 'r')
w = open('out.txt', 'w')
w.write("\n".join(list(set(map(str.strip,f.readlines())))))
出来txt
python
world
hello
如果你想坚持以前的方法,你可以使用:
line_seen = set()
f = open('a.txt', 'r')
w = open('out.txt', 'w')
for i in f:
i = i.strip()
if i not in line_seen:
w.write(i)
line_seen.add(i)
f.close()
w.close()