python - 如何替换我当前所在的行?

标签 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

如何用 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/

相关文章:

python - Keras:预期 activate_3 具有形状 (None, 3),但得到的数组具有形状 (5708, 1)

python - 如何使夹层用户电子邮件不可更新?

python - 如何在 Pyomo 中编写分段线性目标函数

用于播放不同声音的音频的 python 线程,似乎没有正确锁定,并且函数的开头在线程调用后返回

python - 从 Python 字典中弹出许多元素的最佳方法

python - 使用多维特征(输入维度误差)使用 scikit-learn KNN 进行分类

python - 如何向 wx.ScrolledPanel 添加项目?

java - 在 Python/Java 中创建文件时每秒获得写入速度

python - PyQt QtCharts 设计器插件

python - 无法使用 sqlalchemy 查询 json 列