我需要编写一个程序,提示用户输入任何文件名,逐行加载数据,删除任何重复的行,按字母顺序对行排序,并将剩余的行写入另一个文件。你知道吗
我已经完成了大部分代码,但我正在努力按字母顺序排列我的行。有什么建议吗?你知道吗
提前感谢您的帮助!你知道吗
def deleteDuplicateRecords(fileName):
try:
newFileName="filtered_"+fileName
with open(fileName,'r') as readFile, open(newFileName,'w') as writeFile:
lineSet = set()
for line in readFile:
if line not in lineSet:
lineSet.add(line)
writeFile.write(line)
readFile.close()
writeFile.close()
print(f"Duplicate rows removed succesfully. Open the new file '{newFileName}'")
except FileNotFoundError:
print("File Not Found")
name = input("Enter the name of the text file including the proper extension (.txt, .csv, etc): ")
print()
deleteDuplicateRecords(name)
这应该起作用:
注意事项:
with
,则在作用域结束时会自动关闭文件。你知道吗sorted
函数对结果进行排序{line for line in readFile}
使用set comprehension以更简洁的方式从文件行创建一个集合。你知道吗您可以阅读所有排序方法的文档。 https://docs.python.org/3/howto/sorting.html 在此之后,返回排序到您的输出。你知道吗
sorted
对集合排序,它返回一个列表顺便说一句,使用with语句意味着您不需要手动关闭文件。你知道吗
相关问题 更多 >
编程相关推荐