在csv txt或任何其他fi中按字母顺序排列行

2024-10-01 00:17:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个程序,提示用户输入任何文件名,逐行加载数据,删除任何重复的行,按字母顺序对行排序,并将剩余的行写入另一个文件。你知道吗

我已经完成了大部分代码,但我正在努力按字母顺序排列我的行。有什么建议吗?你知道吗

提前感谢您的帮助!你知道吗

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)


Tags: thenameincloseas字母lineopen
3条回答

这应该起作用:

def deleteDuplicateRecords(fileName):
    try:
        newFileName="filtered_"+fileName
        with open(fileName,'r') as readFile, open(newFileName,'w') as writeFile:
            for sorted_line in sorted({line for line in readFile}):
                writeFile.write(sorted_line)
        print(f"Duplicate rows removed successfully. Open the new file '{newFileName}'")
    except FileNotFoundError:
        print("File Not Found")

注意事项:

  1. 正如其他人所提到的,如果您使用with,则在作用域结束时会自动关闭文件。你知道吗
  2. 如果使用集合,则不会将重复项添加到列表中,因此没有理由检查该项是否已存在于列表中
  3. 如果您有一个iterable(list、set等),您可以简单地使用sorted函数对结果进行排序
  4. {line for line in readFile}使用set comprehension以更简洁的方式从文件行创建一个集合。你知道吗

您可以阅读所有排序方法的文档。 https://docs.python.org/3/howto/sorting.html 在此之后,返回排序到您的输出。你知道吗

  1. 将行累加成一组
  2. sorted对集合排序,它返回一个列表
  3. 然后将行写入输出文件

顺便说一句,使用with语句意味着您不需要手动关闭文件。你知道吗

相关问题 更多 >