繁体   English   中英

无法在 python 中的字符串匹配后删除行

[英]not able to delete line after string matches in python

如果与给定字符串不匹配,我正在尝试删除行,但它没有发生

# !/usr/bin/python

import os
import re
import fileinput

rootdir = path

for root, subFolders, files in os.walk(rootdir):
    for file in files:
        with open(os.path.join(root, file), "r") as f:
            lines = f.readlines()
        with open(os.path.join(root, file), "w") as f:
            for line in lines:
                if line.strip("\n") != "@angular/":
                    print(line)
                    f.write(line)

line.strip() 方法不会删除具有“@angular/”的行

您可以使用in关键字查看某些内容是否在序列中,如下所示:

if '@angular/' not in line:
    print(line)
    f.write(line)

要检查一个字符串是否包含另一个字符串,请使用“in”关键字:

if not "@angular/" in line:
    print(line)
    f.write(line)
with open('scrap.txt', encoding='utf-8') as f:
    fi = f.readlines()

fi

["@angular/ sdfhdsfdslkfa;f'a\n",
 'fskfg;lsdkfd\n',
 'dfkdsjgladjgg @angular/ fpopfd;fk\n',
 'dgksgeo[p4w097642utf\n',
 '@angular/ ahafeofij[to hellljdsiohf\n',
 'afkakgAF[\n',
 '\n']

new=[]

for i in range(len(fi)):
    try:
        if re.search(r'@angular/', fi[i]).group():
            print('found in ', i)
    except AttributeError:
        for i in range(len(fi)):
    try:
        if re.search(r'@angular/', fi[i]).group():
            print('found in ', i)
    except AttributeError:
        print(f'not found in {i} so added to new:')
        new.append(fi[i])

output:
------
found in  0
not found in 1 so added to new:
found in  2
not found in 3 so added to new:
found in  4
not found in 5 so added to new:
not found in 6 so added to new:

print(new)
['fskfg;lsdkfd\n', 'dgksgeo[p4w097642utf\n', 'afkakgAF[\n', '\n']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM