【问题标题】:Sorting a list but I keep getting a error对列表进行排序,但我不断收到错误消息
【发布时间】:2022-01-11 22:59:13
【问题描述】:

我仍然是 python 初学者。我需要将 2 个列表写入两个不同的文本文件,然后对每个文本文件进行排序,最后将这两个文本文件输出添加到一个也已排序的新文本文件中。 我需要对升序进行排序。当我这样做时,我尝试将数字转换为 str,程序可以打印未排序的列表,但是当我添加排序时问题出现了。希望这是有道理的。

number1 = [5000, 300, 4, 1, 2]
number2 = [19, 66, 8, 17, 100]

with open("numbers1.txt", "w") as file1:
    file1.write(str(number1))

with open("numbers2.txt", "w") as file2:
    file2.write(str(number2))

with open("numbers1.txt", "r+") as file1:
    content = file1.read()
    content.sort()
    print(content)

with open("numbers2.txt", "r+") as file2:
    content2 = file2.read()
    content2.sort()
    print(content2)
    

#combined =  file1 + file2
#combined.sort()
#print(combined) 

程序然后给我这个错误

content.sort()
AttributeError: 'str' object has no attribute 'sort'

我还没有将最后两个排序列表写入一个也排序的新文本文件

【问题讨论】:

  • read()返回的对象类型为字符串。就像您在将列表写入文件时将其转换为字符串一样,您希望在从文件中读取它时将其转换回来。

标签: python list sorting


【解决方案1】:

file.read() 返回一个字符串,而不是一个列表。如果需要列表,则需要将其转换回列表,但首先将列表保存到文件的格式并不是最好的,因为它会创建额外的字符。

将列表的一个元素写入文件的每一行可能是一个更好的主意。然后,读取文件

with open("numbers1.txt", "w") as file1:
    file1.writelines(str(n) for n in number1)

with open("numbers1.txt", "r+") as file1:
    content = []
    for line in file1:
        content.append(int(line))

    content.sort()

您可以用理解替换读取循环:

with open("numbers1.txt", "r+") as file1:
    content = [int(line) for line in file1]
    content.sort()

如果是一个选项,您可以写入 json 文件而不是常规文本文件。当您使用json.load() 时,json 包负责将读取列表转换为正确的格式。

import json

with open("numbers1.json", "w") as file1:
    json.dump(numbers1, file1)

with open("numbers1.txt", "r+") as file1:
    content = json.load(file1)
    content.sort()

【讨论】:

    【解决方案2】:

    查看内置模块pathlib

    
    import json
    from pathlib import Path
    
    AppRoot: Path = Path('.')
    path_text: Path  = AppRoot / 'numbers.txt'
    path_json: Path  = AppRoot / 'numbers.json'
    

    @Pranav Hosangadi 的例子:

    with open("numbers1.json", "w") as file1:
        json.dump(numbers1, file1)
    
    with open("numbers1.txt", "r+") as file1:
        content = json.load(file1)
        content.sort()
    

    可以写成

    content = json.loads(path_text.read_text())
    content.sort()
    path_json.write_text(json.dumps(content))
    

    因为我保存了AppRoot,所以我可以从任何目录引用,例如

     `.../YourApp/Config/settings.json`
    

    不管调用者是什么子目录。移动文件或将您的应用移动到另一个父级不会中断。

    【讨论】:

      猜你喜欢
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2011-12-13
      • 2014-04-12
      • 1970-01-01
      • 2023-01-13
      • 2022-11-09
      相关资源
      最近更新 更多