美文网首页
Python中txt的简单操作

Python中txt的简单操作

作者: 陈芝麻烂谷子的事 | 来源:发表于2021-03-02 20:09 被阅读0次

    Python操作txt文件的基础操作记录,包含新建文件、读取文件、写入文件、替换文件、修改文件后缀和插入数据。
    1.新建txt文件

     import os
     file = open(name,"w", encoding='utf-8')
    

    2.读取txt文件:

    baseapi = open("base.txt", encoding='utf-8')
    for b in baseapi:
        print(b)
    

    3.写入txt:

     import os
     file = open(name,"w", encoding='utf-8')
     file.write("111")
    

    4.替换txt中的某一项内容:

      basefile = open("1.txt", encoding='utf-8')
          for i in basefile:
              if "替换的原文字" in i:
                  i = i.replace("替换的原文字","新的文字")
            basefile.write("111")
    

    5.修改文件后缀:

        def refactofilename(file):
            pathfile = os.path.splitext(file)
            if pathfile[1] == ".jmx":
                new_name = pathfile[0]+".txt
                os.rename(file,new_name)
            elif pathfile[1] == ".txt":
                new_name = pathfile[0]+".jmx"
                os.rename(file,new_name)
    

    6.在txt第一行插入文本

    with open('1.txt', 'r+') as f:
        content = f.read()        
        f.seek(0, 0)
        f.write('aaaaaa\n'+content)
    

    7.在txt最后一行插入文本

    with open("D:\\test.txt", encoding="utf-8","a") as data:  
        data.write("aaaa")  
    

    相关文章

      网友评论

          本文标题:Python中txt的简单操作

          本文链接:https://www.haomeiwen.com/subject/topxqltx.html