【问题标题】:Skip few lines during writing to file in python在 python 中写入文件时跳过几行
【发布时间】:2021-06-28 10:15:13
【问题描述】:

我正在使用 fileinput.FileInput 从文件中获取读取行。

for line in fileinput.FileInput("abc.txt",inplace=1):
    if matching_string in line:
        #print few lines
    print line,

比如abc.txt就是

Hello
World
This is
Python
Script
Bye

matching_string 是“This”。 我希望输出“abc.txt”为:

Hello
World
File changed
C++
Script
Bye

我需要修改中间的一些行,并且要跳过的行数不固定。有时,我可能需要像上面的例子一样跳过 2 行,有时只需要 1 行或更多行。

【问题讨论】:

  • print line, 不是有效的 Python 3.x 语法,它应该是 print(line)

标签: python python-3.x file-io scripting


【解决方案1】:

fileinput 对象分配给一个变量。然后你可以使用next() 读取循环体内的一行。

with fileinput.FileInput("abc.txt",inplace=1) as f:
    for line in f:
        if matching_string in line:
            #print few lines
            next(f) # skip over the next input line
        print(line)

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 2016-01-31
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多