场景
想要利用 python 读取指定文件的中的内容,格式自行解析,然后将读取到的内容整理后再写入另一个文件中
步骤
- 读取文件
- 将读取出来的每一行内容自定义修改一下
- 将修改后的内容写入到另一个文件中
本地测试代码
# 打开源文件并读取其内容
with open('source.txt', 'r') as source_file:content = source_file.read()# 打开目标文件以写入模式(这里假设是覆盖原有内容)
with open('target.txt', 'w') as target_file:# 将读取到的字符串写入目标文件target_file.write(content)# 使用 with 语句时,文件会在上下文结束时自动关闭,无需显式调用 close()
读取每一行内容
def read_file_and_write(source_file, target_file):with open(source_file, 'r') as file:finalList = []# for就是在迭代文件中的每一行内容 读取每一行for line in file:# ....# ....# ....对line 的操作finalList.append(line )# 写入目标文件with open(target_file, "w") as dstFile:for item in finalList:dstFile.write(item)dstFile.write("\n")