Python中txt的简单操作

2021-03-02  本文已影响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")  
上一篇下一篇

猜你喜欢

热点阅读