我有这样一段 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
如何用 s.th. 替换行我想写什么?
最佳答案
使用 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)
关于python - 如何替换我当前所在的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16216459/