环境:python3.7.5
文本文件的内容如下:
在这里插入图片描述
想在’foo1 bar3’和’foo2 bar4’之间插入’渣渣猫’
方法一:

import fileinput

processing_foo1s = False

for line in fileinput.input('data.txt', inplace=2):
  if line.startswith('foo1'):
    processing_foo1s = True
  else:
    if processing_foo1s:
      print('渣渣猫\n ')
    processing_foo1s = False
  print(line)

程序运行结果
在这里插入图片描述
问题:python逐行读取文件,输出后为什么有空行?
每一行末尾都有一个\n换行符,print()执行一次末尾也是有个换行,所以两个加一起看起来是多了一个空行,输出的时候改成print(line,end=‘’)

import fileinput

processing_foo1s = False

for line in fileinput.input('Txt_Insert_2.txt', inplace=2):
  if line.startswith('foo1'):
    processing_foo1s = True
  else:
    if processing_foo1s:
      print('渣渣猫')
    processing_foo1s = False
  print(line,end='')

运行结果
在这里插入图片描述
fileinput模块提供处理一个或多个文本文件的功能,可以通过使用for循环来读取一个或多个文本文件的所有行。

fileinput.input (files='filename', inplace=False, backup='', bufsize=0, mode='r', openhook=None)
1 files:         #文件的路径列表,默认是stdin方式,多文件['1.txt','2.txt',...]
2 inplace:       #是否将标准输出的结果写回文件,默认不取代
3 backup:        #备份文件的扩展名,只指定扩展名,如.bak。如果该文件的备份文件已存在,则会自动覆盖。
4 bufsize:       #缓冲区大小,默认为0,如果文件很大,可以修改此参数,一般默认即可
5 mode:      #读写模式,默认为只读
6 openhook:    #该钩子用于控制打开的所有文件,比如说编码方式等;       

方法二
在这里插入图片描述

import shutil

txt = 'data1.txt'
tmptxt = '1.txt.tmp'

with open(tmptxt, 'w') as outfile:
    with open(txt, 'r') as infile:
        flag = 0
        for line in infile:
            if not line.startswith('foo1') and flag == 0:
                outfile.write(line)
                continue
            if line.startswith('foo1') and flag == 0:
                flag = 1
                outfile.write(line)
                continue
            if line.startswith('foo1') and flag == 1:
                outfile.write(line)
                continue
            if not line.startswith('foo1') and flag == 1:
                outfile.write('土拨鼠\n')
                outfile.write(line)
                flag = 2
                continue
            if not line.startswith('foo1') and flag == 2:
                outfile.write(line)
                continue

shutil.move(tmptxt, txt)

在这里插入图片描述
方法三:
在这里插入图片描述

fp = open('data.txt','r+',encoding='gbk')
lines = []
for line in fp:
    line = line.strip()
    lines.append(line)
fp.close()

lines.insert(6, 'Nick Judy') # 在第七行插入
#lines = str(lines)
s = "\n".join(lines)
fp = open('data.txt', 'w')
fp.write(s)
fp.close()

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐