导入 os 和 random 模块

import os import random

创建或清空文件

def create_file(file_path): # 判断文件是否存在 if os.path.exists(file_path): # 如果文件存在,询问用户是否删除并创建新文件 confirm = input("文件已存在,是否删除并创建新文件?(y/n)") if confirm.lower() == "y": os.remove(file_path) # 删除文件 else: return False # 创建空文件 with open(file_path, "w") as f: pass print("已创建文件 {}!".format(file_path)) return True

写入随机数

def write_random_numbers(file_path): numbers = [] # 生成随机数,直到满足条件:有两个负数或零 while len(numbers) < 2 or all(num >= 0 for num in numbers): numbers = [round(random.uniform(-1, 1), 2) for _ in range(10)] # 将随机数写入文件 with open(file_path, "w") as f: for num in numbers: f.write(str(num) + "\n") print("已写入 10 个随机数据!") print("从 {} 中读取到的数据为:".format(file_path)) print(",".join(str(num) for num in numbers)) return numbers

读取文件并排序

def sort_numbers(file_path): with open(file_path) as f: # 将文件中的每一行转换为浮点数,并存储到列表中 numbers = [float(line.strip()) for line in f] # 对列表中的数进行排序,从大到小排列 numbers.sort(reverse=True) # 将排序后的数字转换为字符串,并拼接起来 result = "".join(str(num) for num in numbers) print("排序之后得到的字符串为:") print(result) return result

处理字符串

def process_string(string): # 将字符串中的小数点和前导零去掉 string = string.replace(".", "").lstrip("0") print("经过处理之后的字符串为:") print(string) return string

计算表达式

def calculate(string): # 使用 eval 函数计算表达式的值 result = eval(string) # 将结果转换为整数,并使用千位分隔符格式化 result_str = "{:,}".format(int(result)) # 将结果追加到文件末尾 with open(file_path, "a") as f: f.write("," + result_str) print("最终得到的值为:{}".format(result_str)) print("已追加该数值!")

移动文件

def move_file(file_path): # 将文件移动到当前目录下,并改名为 "test_solved.txt" new_path = os.path.join(os.getcwd(), "test_solved.txt") os.replace(file_path, new_path) print("已移动到当前目录!") print("已改名!")

主程序

if name == "main": # 定义文件路径 file_path = os.path.join(os.path.expanduser("~"), "Desktop", "test.txt") # 创建文件,如果文件已存在则询问用户是否删除并创建新文件 success = create_file(file_path) if success: # 写入随机数,并返回写入的数字列表 numbers = write_random_numbers(file_path) # 读取文件并排序,返回排序后的字符串 result = sort_numbers(file_path) # 处理字符串,返回处理后的字符串 processed = process_string(result) # 计算表达式,并将结果追加到文件末尾 calculate(processed) # 将文件移动到当前目录下,并改名为 "test_solved.txt" move_file(file_path) print("程序运行完毕!"

对代码import osimport random# 创建或清空文件def create_filefile_path if ospathexistsfile_path confirm = input文件已存在是否删除并创建新文件?yn if confirmlower == y osremovefile_path else

原文地址: https://www.cveoy.top/t/topic/dIMa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录