Reputation: 73
How to extract a text in a file with python. - A text begin with chaine.
My code is
fichier= open("Service.txt", "r")
for ligne in fichier:
if ligne==chaine:
#What do I do ?
fichier.close()
Upvotes: 3
Views: 171
Reputation: 1650
with open("Service.txt", "r") as fichier:
for ligne in fichier.readlines():
if 'Call' in ligne:
#What do I do
Try this.
Upvotes: 0
Reputation: 73
Thank you all.
This is a file (Service.txt) while, I use to recover a text with it.
A text is only:
Supplementary service = Call forwarding unconditional
= Call waiting
= Calling line identification presentation
Thank you.
Upvotes: 0
Reputation: 39616
If I understood question correctly:
test.txt
fsdfj ljkjl
sdfsdf ljkkk
some ldfff
fffl lll
ppppp
script:
chaine = 'some'
with open("test.txt", "r") as f:
text = f.read()
i = text.find(chaine)
print(text[i:])
output:
some ldfff
fffl lll
ppppp
Upvotes: 2
Reputation: 15537
with open("Service.txt", "r") as f:
lines = f.readlines()
chaines = [line for line in lines if line.startswith("chaine")]
for chaine in chaines:
print("Some chaine, whatever that is", chaine)
This uses a list comprehension, the if
part will filter out any line that doesn't start with "chaine"
.
The with
block is a context manager, it makes sure to close the file when the block ends, even if there is an exception.
Upvotes: 1
Reputation: 21506
You can try like this,
>>> with open('Service.txt', 'r') as f:
... val = f.read()
>>> if "cheine" in val:
... # do something
Upvotes: 0
Reputation: 21317
You have to check in
operator with string.
Like
>>> a = "cheine is good"
>>> "cheine" in a
True
So your code must be like.
fichier= open("Service.txt", "r")
for ligne in fichier:
if chaine in ligne:
#What do I do ?
fichier.close()
If you have to check start only in line, then you can check ligne.startswith
.
Upvotes: 1