Python 代码:将文本文件中的整数降序排序并写入新文件
以下是一个示例的 Python 代码,用于读取桌面上的 'data.txt' 文件中的整数,并将其按降序写入 'data_asc.txt' 文件中:
import os
# 读取整数并存储到列表中
numbers = []
desktop_path = os.path.expanduser('~/Desktop')
file_path = os.path.join(desktop_path, 'data.txt')
with open(file_path, 'r') as file:
for line in file:
number = int(line.strip())
numbers.append(number)
# 对列表中的整数进行降序排序
numbers.sort(reverse=True)
# 将排序后的整数写入文件
output_file_path = os.path.join(desktop_path, 'data_asc.txt')
with open(output_file_path, 'w') as file:
for number in numbers:
file.write(str(number) + '\n')
print('整数已按降序写入文件 data_asc.txt')
请确保在执行代码之前,在桌面上存在 'data.txt' 文件,并且文件中每行都包含一个整数。代码会自动将结果写入名为 'data_asc.txt' 的文件中。
原文地址: https://www.cveoy.top/t/topic/U6k 著作权归作者所有。请勿转载和采集!