i'm trying to remove line if doesn't match with given string, but its not happening
# !/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() method doesn't remove line which has '@angular/'
You can see if something is in a sequence with the in keyword like this:
if '@angular/' not in line:
print(line)
f.write(line)
To check if one string contain another string, use the "in" keyword:
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.