import os
with open("file.txt", "r") as infile:
numbers = set()
f = open("_file.txt", "w")
for line in infile:
tokens = line.split(',')
if int(tokens[0]) not in numbers:
numbers.add(int(tokens[0]))
f.write(line)
f.close()
os.remove("file.txt")
os.rename("_file.txt", "file.txt")
# Read your entire file into memory.
my_file = 'my_file.txt'
with open(my_file) as f_in:
content = f_in.readlines()
# Keep track of the numbers that have already appeared
# while rewriting the content back to your file.
numbers = []
with open(my_file, 'w') as f_out:
for line in content:
number, country = line.split(',')
if not number in numbers:
f_out.write(line)
numbers.append(number)
import sets
seen = sets.Set()
with open('in.txt', 'r'), open('out.txt', 'w') as fr, fw:
for line in fr:
row = line.split(',')
if row[0] not in seen:
fw.write(line)
seen.add(row[0])
我希望这是最容易理解的。在
相关问题 更多 >
编程相关推荐