首页 > 解决方案 > 我如何附加文本文件来订购内容

问题描述

我有一个包含大约 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)

标签: python

解决方案


你需要:

  • 读取文件的内容:open('file.txt', 'r').read()。
  • 使用分隔符拆分内容:separator.split(contents)
  • 将每个项目转换为数字,否则,您将无法按数字排序:int(item)
  • 对数字进行排序: sorted(list_of_numbers)

这是一个代码示例,假设文件是​​空格分隔的并且数字是整数:

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)

推荐阅读