以下是一个示例代码,用于比较本地文件中的数字,并在数字高于本地数字时进行覆盖。
import os
def compare_and_replace(file_path, new_number):
if os.path.isfile(file_path):
with open(file_path, 'r') as file:
current_number = int(file.read().strip())
if new_number > current_number:
with open(file_path, 'w') as file:
file.write(str(new_number))
print("文件已更新")
else:
print("新数字不大于当前数字")
else:
print("文件不存在")
file_path = "path/to/file.txt" # 替换为实际文件路径
new_number = 100 # 替换为实际要比较的数字
compare_and_replace(file_path, new_number)
该代码首先检查文件是否存在,如果存在则读取文件中的当前数字。然后,它将新数字与当前数字进行比较。如果新数字大于当前数字,则将新数字写入文件并显示"文件已更新"。否则,显示"新数字不大于当前数字"。如果文件不存在,则显示"文件不存在"。请记得将file_path
和new_number
替换为实际的文件路径和要比较的数字。
上一篇:比较本地文本文件与在线文件
下一篇:比较本月销售额与上月销售额。