当前位置:   article > 正文

python 读取文件内容每一行,写入另一个文件内_python读取txt文件 查找正确的数据写入新的文件

python读取txt文件 查找正确的数据写入新的文件

场景

想要利用 python 读取指定文件的中的内容,格式自行解析,然后将读取到的内容整理后再写入另一个文件中

步骤

  1. 读取文件
  2. 将读取出来的每一行内容自定义修改一下
  3. 将修改后的内容写入到另一个文件中

本地测试代码

# 打开源文件并读取其内容
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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

读取每一行内容

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")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
'
运行
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/803050
推荐阅读
相关标签
  

闽ICP备14008679号