I'm still a python beginner. I need to write 2 lists to two different text files then sort each text file then finally add those two text file outputs to a new text file that is also sorted. I need to sort the ascending order.I tried casting the numbers to str when I did this the program worked to print the unsorted list but the problem came when I added sort .Hope this makes sense.
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)
the program then gives me this error
content.sort()
AttributeError: 'str' object has no attribute 'sort'
I have yet to write the final two sorted lists to a new text file that is also sorted
CodePudding user response:
file.read()
returns a string, not a list. You need to convert it back to a list if you want a list, but the format in which you're saving the list to the file in the first place isn't the best, since it creates extra characters.
It's probably a better idea to write one element of the list to each line of the file instead. Then, read the file
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()
You could replace the read loop with a comprehension:
with open("numbers1.txt", "r ") as file1:
content = [int(line) for line in file1]
content.sort()
If it is an option, you could write to a json file instead of a regular text file. The json
package takes care of converting the read list to the correct format when you use json.load()
.
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()