【发布时间】: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()返回的对象类型为字符串。就像您在将列表写入文件时将其转换为字符串一样,您希望在从文件中读取它时将其转换回来。