如何更换我目前的线路?

gur*_*gui 2 python

我有一个像这样的python代码:

with open('myFile') as f:
        next(f) # skip first line
        for line in f:
            items = line.split(';')
            if len(items) < 2:
                # now I want to replace the line with s.th. that i write
Run Code Online (Sandbox Code Playgroud)

如何用s.th.替换线 我想写什么?

iru*_*var 6

使用fileinput模块的就地功能.请参阅fileinput上的可选就地过滤部分.像这样的东西:

import fileinput
import sys
import os

for line_number, line in enumerate(fileinput.input('myFile', inplace=1)):
  if line_number == 0:
    continue
  items = line.split(';')
  if len(items) < 2:
    sys.stdout.write('blah' + os.linesep)
  else:
    sys.stdout.write(line)
Run Code Online (Sandbox Code Playgroud)