赞
踩
想要利用 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")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。