我正在尝试创建一个简单的程序,从文件中删除重复行。然而,我被困住了。我的目标是最终删除除1重复行之外的所有内容,这与建议的重复不同。所以我还有那些数据。我也希望这样做,它接受相同的文件名,并输出相同的文件名。当我试图使文件名和文件名相同时,它只输出一个空文件。
input_file = "input.txt"
output_file = "input.txt"
seen_lines = set()
outfile = open(output_file, "w")
for line in open(input_file, "r"):
if line not in seen_lines:
outfile.write(line)
seen_lines.add(line)
outfile.close()input.txt
I really love christmas
Keep the change ya filthy animal
Pizza is my fav food
Keep the change ya filthy animal
Did someone say peanut butter?
Did someone say peanut butter?
Keep the change ya filthy animal预期产出
I really love christmas
Keep the change ya filthy animal
Pizza is my fav food
Did someone say peanut butter?发布于 2018-12-29 23:30:43
无论您做什么,行outfile = open(output_file, "w")都会截断您的文件。下面的读取将找到一个空文件。我建议安全地使用一个临时文件:
这比两次打开文件进行读写要健壮得多。如果出了什么问题,你就会把原来的和你做过的任何工作都藏起来。如果在过程中出现任何问题,您的当前方法可能会破坏您的文件。
下面是一个使用tempfile.NamedTemporaryFile的示例和一个with块,以确保即使发生错误,也能正确关闭所有内容:
from tempfile import NamedTemporaryFile
from shutil import move
input_file = "input.txt"
output_file = "input.txt"
seen_lines = set()
with NamedTemporaryFile('w', delete=False) as output, open(input_file) as input:
for line in open(input_file, "r"):
sline = line.rstrip('\n')
if sline not in seen_lines:
output.write(line)
seen_lines.add(sline)
move(output.name, output_file)即使输入和输出名称相同,最后的move也将正确工作,因为output.name保证与两者有所不同。
还要注意,我正在从集合中的每一行中剥离换行符,因为最后一行可能没有换行符。
Alt溶液
如果您不关心行的顺序,则可以通过直接在内存中执行所有操作来简化流程:
input_file = "input.txt"
output_file = "input.txt"
with open(input_file) as input:
unique = set(line.rstrip('\n') for line in input)
with open(output_file, 'w') as output:
for line in unique:
output.write(line)
output.write('\n')你可以把这个和
with open(input_file) as input:
unique = set(line.rstrip('\n') for line in input.readlines())
with open(output_file, 'w') as output:
output.write('\n'.join(unique))第二个版本做的事情完全一样,但同时加载和写入。
发布于 2018-12-29 23:24:12
问题是,您正在尝试写入您正在读取的同一个文件。你至少有两个选择:
备选案文1
使用不同的文件名(例如input.txt和output.txt)。在某种程度上来说,这是最简单的。
选项2
从输入文件中读取所有数据,关闭该文件,然后打开该文件进行写入。
with open('input.txt', 'r') as f:
lines = f.readlines()
seen_lines = set()
with open('input.txt', 'w') as f:
for line in lines:
if line not in seen_lines:
seen_lines.add(line)
f.write(line)选项3
使用r+模式打开文件进行读写。在这种情况下,您需要小心,在编写之前读取将要处理的数据。如果您在单个循环中执行所有操作,则循环迭代器可能会丢失跟踪。
发布于 2018-12-29 23:28:19
import os
seen_lines = []
with open('input.txt','r') as infile:
lines=infile.readlines()
for line in lines:
line_stripped=line.strip()
if line_stripped not in seen_lines:
seen_lines.append(line_stripped)
with open('input.txt','w') as outfile:
for line in seen_lines:
outfile.write(line)
if line != seen_lines[-1]:
outfile.write(os.linesep)输出:
I really love christmas
Keep the change ya filthy animal
Pizza is my fav food
Did someone say peanut butter?https://stackoverflow.com/questions/53974070
复制相似问题