首次出现字符串写入函数时不写入任何内容

时间:2018-04-07 17:55:11

标签: python

功能:

def newstr(string, file_name, after):
    lines = []
    with open(file_name, 'r') as f:
        for line in f:
            lines.append(line)
    with open(file_name, 'w+') as f:
        flag = True
        for line in lines:
            f.write(line)
            if line.startswith(after) and flag:
                f.write(string+"\n")
                flag = False

我正在运行的是什么

newstr('hello', "test.txt", "new code(")

Test.txt内容:

package example.main;

import example
public class Main {
    public static void Main() {
        new code("<RANDOM>");
        new code("<RANDOM>");
    }   

}

我的期望:

package example.main;

import example
public class Main {
    public static void Main() {
        new code("<RANDOM>");
        hello
        new code("<RANDOM>");
    }   

}

但是当我运行脚本时没有任何变化。

3 个答案:

答案 0 :(得分:1)

您有空格缩进的行,例如

        new code("<RANDOM>");

该行开头有空格;如果您查看字符串表示,请参阅:

>>> repr(line)
'        new code("<RANDOM>");\n'

该行不以'new code('开头,而是以' new code('开头:

>>> line.startswith('new code(')
False

str.startswith()不会忽略空格。

剥离空格,或在after变量中包含空格:

>>> line.strip().startswith('new code(')  # str.strip removes whitespace from start and end
True
>>> line.startswith('        new code(')
True

您还可以使用regular expressions来匹配行,因此请使用模式r'^\s*new code\('

答案 1 :(得分:1)

你的错误是该行以你正在寻找的文字开头。它以" new code("而不是"new code(开头。因此,您需要查找" new code(,或者需要从该行中删除空格,即line.lstrip().startswith(...

顺便说一句。而不是你用来读取文件的循环,你可以说lines = f.readlines()

答案 2 :(得分:0)

由于IDE创建了大量空白 您需要先删除它才能使用startswith,然后将其更改为line.lstrip().startswith,以便删除前导空格 接下来,您可以使用正则表达式将空格添加到新行中,如此

f.write(re.search(r"\s*", line).group()+string+"\n")

固定代码:

import re
def newstr(string, file_name, after):
    with open(file_name, 'r') as f:
        lines = f.readlines()
    with open(file_name, 'w+') as f:
        flag = True
        for line in lines:
            f.write(line)
            if line.lstrip().startswith(after) and flag:
                f.write(re.search(r"\s*", line).group()+string+"\n")
                flag = False

newstr('hello', "test.txt", "new code(")