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)
解决方案
你需要:
- 读取文件的内容: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)
推荐阅读
- ssas - 为什么要使用 Process Data 与 Process Full 来处理分区
- assembly - 为什么 lw 和 sw 的 ALU 操作码是 00?
- python - Python 中的容器转换函数有多贵?
- c - 为什么在 c 中打印字符串数组不提供相同的输出?
- r - 将 sp 转换为 data.frame - r 时保留小数位
- openmp - OpenMP 创建的多个进程
- python - 简单的循环任务
- javascript - 如何在反应中只接受电话号码
- amazon-web-services - 从 Lagom 连接到 AWS Managed Cassandra 服务
- powershell - 在 foreach 循环中排除多个 OU