我有一个约2000个数字的文本文件,它们以随机顺序写入文件...我如何从python中对其进行排序?感谢您的帮助
file = open('file.txt', 'w', newline='')
s = (f'{item["Num"]}')
file.write(s + '\n')
file.close()
read = open('file.txt', 'a')
sorted(read)
答案 0 :(得分:1)
您需要:
这是一个代码示例,假设文件是用空格分隔并且数字是整数:
import re
file_contents = open("file.txt", "r").read() # read the contents
separator = re.compile(r'\s+', re.MULTILINE) # create a regex separator
numbers = []
for i in separator.split(f): # use the separator
try:
numbers.append(int(i)) # convert to integers and append
except ValueError: # if the item is not an integer, continue
pass
sorted_numbers = sorted(numbers)
您现在可以将排序后的内容附加到另一个文件:
with open("toappend.txt", "a") as appendable:
appendable.write(" ".join(sorted_numbers)