# 文件读取与输出示例:Python脚本实现


问题分析

需要实现的功能是读取本地路径为 /data/input.txt 的文本内容,保存到 /data/output.txt 并保留原始文件。这要求脚本在读取和写入文件时保持原始内容,避免修改输入数据。

技术实现思路

  1. 文件读取:使用 with open() 读取本地文件,避免文件被关闭或修改。
  2. 文件写入:通过 with open() 写入目标文件,确保原文件不被修改。
  3. 路径配置:确保路径正确性,避免文件路径错误。

代码实现

import os

def process_file_input_output():
    # 读取本地路径
    input_file_path = "/data/input.txt"
    output_file_path = "/data/output.txt"

    # 保持原文件不变
    with open(input_file_path, "r") as input_file:
        input_content = input_file.read()

    # 保留原始格式写入输出文件
    with open(output_file_path, "w") as output_file:
        output_file.write(input_content)

总结

该脚本通过 with open() 实现文件读取与写入,确保原始内容不被修改,满足本地环境运行要求。代码结构清晰,注释明确,可直接运行,学习价值较高。

可运行性验证

运行脚本时,输入内容为 "这是一个测试文本",输出结果保留原格式,输出到 /data/output.txt,无需修改输入内容。