首页 > 编程语言 >#yyds干货盘点#Python读写文件脚本

#yyds干货盘点#Python读写文件脚本

时间:2023-04-09 23:32:53浏览次数:41  
标签:yyds stream Python 干货 file output path line match

该脚本根据输入的路径,可以读取路径下的所有文件,实现匹配字符串替换,添加内容和删除内容的功能。

import os
from fileinput import FileInput

#删除内容
def match_then_delete(inputpath):
    for root,dirs,files in os.walk(inputpath):
        for file in files:
            path = os.path.join(root,file)
            output_file_path = ""+file
            print(out_file_path)
            with open(path,'r',encoding='gbk') as infile:
                input_stream=infile.read()
                output_stream=""
                #换行分切分内容
                input_stream_lines=input_stream.split("\n")
                for line in input_stream_lines:
                    if line.startwith(""):
                        pass
                    else:
                        output_stream=output_stream+line+'\n'
                #读取去掉指定内容后的新内容,重新写文件
                g = open(output_file_path,'w')
                g.write(output_stream)

#添加内容,在匹配内容match上方添加内容content
def match_then_insert(filename,match,content):
    for line in FileInput(filename,inplace=True):
        if match in line:
            line = content+'\n'+line
        print(line,end='')

#匹配字符串替换
def match_then_replace(filename,oldtext,newtext):
    for line in FileInput(filename, inplace=True):
        if oldtext in line:
            line = line.replace(oldtext,newtext)
        print(line,end='')

if __name__=='__main__':
    inputpath = ""
    for root,dirs,files in os.walk(inputpath):
        for file in files:
            path = os.path.join(root,file)
            output_file_path = inputpath+file
            match_then_replace(output_file_path,"oldtext","newtext")

需要注意的点:
当我们需要处理的文件是utf-8编码时,而python3中默认的文件解码格式是gbk,若直接使用FileInput模块,会报错误
UnicodeDecodeError: 'gbk' codec can't decode byte 0x89 in position 116: illegal multibyte sequence
若我们使用如下形式

for line in fileinput.input(filename,openhook=fileinput.hook_encoded('utf-8','')

使用openhook指定编码格式为utf-8时,此时则无法设置inplace=True,即无法写入文件
这里使用的解决办法是修改fileinput的源码,在340和360行附近,在代码中加入enconding="utf-8"

#yyds干货盘点#Python读写文件脚本_写入文件

标签:yyds,stream,Python,干货,file,output,path,line,match
From: https://blog.51cto.com/u_11365839/6179266

相关文章

  • Python ORM Pony PostgreSQL数据库 常用操作
    Pony是一个高级的对象关系映射器ORM框架。Pony它能够使用Python生成器表达式和lambdas向数据库编写查询。Pony分析表达式的抽象语法树,并将其转换为SQL查询。支持SQLite,MySQL,PostgreSQL和Oracle等数据库,本文主要介绍PythonORMPony中PostgreSQL数据库常用操作,及数据增加、删除......
  • Python同Java及C++的不同之处
    Python同Java及C++的不同之处1.C++、Java对变量的定义很严格比如inta=0python则直接定义a=02.C++、Java代码结束时需要用;隔开比如inta=0;,而python则不用a=0直接换行即可3.C++、Java中的循环或者判断需要用{}括起来for(i=0;i<5;i++){},python使用:forii......
  • python3中Requests将verify设置为False后,取消警告的方式
    importrequestsresp=requests.get('https://www.***.com',verify=False)调用成功但是会有如下警告信息:InsecureRequestWarning:UnverifiedHTTPSrequestisbeingmadetohost'www.jhnews.com.cn'.Addingcertificateverificationisstronglyadvised.Se......
  • python - datetime日期加减
    importdatetimenow=datetime.datetime.now()#now=datetime.datetime(2023,4,9)now.strftime('%Y-%m-%d%H:%M:%S')#2023-04-0921:00:41#加7天delta7=datetime.timedelta(days=7)(now+delta7).strftime('%Y-%m-%d%H:%M:%S')#2023-04-......
  • python 多进程
    背景:串行执行慢,考虑使用多进程来加速。1多进程这块可以参考:https://blog.csdn.net/Hao_ge_666/article/details/1205717312多线程这块可以参考:https://blog.csdn.net/Hao_ge_666/article/details/1206030143进程池参考:https://zhuanlan.zhihu.com/p/568073350当任务需......
  • python time测试
    pythontime测试 importtimedeftimer(seconds):start_time=time.time()whileTrue:elapsed_time=time.time()-start_timeifelapsed_time>=seconds:breakprint("Time'sup!")timer(10)......
  • golang 编译碰到问题 Package python-2.7 was not found in the pkg-config search pa
    golang运行单测或者编译程序时提示需要配置PKG_CONFIG_PATH环境变量,原因是在程序里使用了go-python包,要求运行环境有python2.7,并设置PKG_CONFIG_PATH环境变量,解决方案如下:#pkg-config--cflags--python-2.7Packagepython-2.7wasnotfoundinthepkg-configsear......
  • python 提取字符中的数字
      一、isdigit()函数isdigit()函数是检测输入字符串是否只由数字组成。如果字符串只包含数字则返回True否则返回False。1234567891011dream="123456"print(dream.isdigit())#返回:True dream="123abc456"print(dream.isdigit())#返回:Fa......
  • [oeasy]python0131_[趣味拓展]各种符号_汉语拼音符号_中文全角英文字母_中文全角标点
    各种符号回忆上次内容中文字符可以有各种分类方法声母拼音检字法韵母合辙押韵的分类偏旁部首实际上unicode的排序方法我们以前勇闯地下城时候获得了一把屠龙宝刀给他镶上了❤️宝石这宝石应该如何理解?今天我们就来彻底解密红色爱心的原理闭环首先是文字我们的汉字可以构成一个闭......
  • [oeasy]python0131_[趣味拓展]各种符号_汉语拼音符号_中文全角英文字母_中文全角标点
    各种符号回忆上次内容中文字符可以有各种分类方法声母拼音检字法 韵母合辙押韵的分类 偏旁部首实际上unicode的排序方法  ​ 添加图片注释,不超过140字(可选) 我们以前勇闯地下城时候获得了一把屠龙宝......