如何附加文本文件来排序内容

2024-04-24 14:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件txtcloseread排序顺序newline数字
1条回答
网友
1楼 · 发布于 2024-04-24 14:31:49

你需要:

  • 读取文件的内容:open('文件.txt','r').read()。你知道吗
  • 使用分隔符拆分内容:分隔符.split(目录)
  • 将每个项目转换为一个数字,否则,您将无法按数字排序:int(item)
  • 数字排序:排序(数字列表)

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

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)

相关问题 更多 >