Printing the lines after matching text - python

I am trying to print the line that is after text matched in the text file.
Something like this:
import re
afterlines=3
with open(filename, 'r') as f:
for line in f:
if line.strip()== ls_losses:
row = f.readline(+afterlines)
print (row)
print ("true")

I would just use a temporary counter.
import re
afterlines=3
temporary_lines = ''
with open(filename, 'r') as f:
for line in f:
if line.strip() == ls_losses:
counter = afterlines
if counter > 0:
temporary_lines += f.readline()
counter -= 1
else:
print(temporary_lines)
temporary_lines = '' # Reinitialize to get ready for the next match
print ("true")

Related

Lines missing in python

I am writing a code in python where I am removing all the text after a specific word but in output lines are missing. I have a text file in unicode which have 3 lines:
my name is test1
my name is
my name is test 2
What I want is to remove text after word "test" so I could get the output as below
my name is test
my name is
my name is test
I have written a code but it does the task but also removes the second line "my name is"
My code is below
txt = ""
with open(r"test.txt", 'r') as fp:
for line in fp.readlines():
splitStr = "test"
index = line.find(splitStr)
if index > 0:
txt += line[:index + len(splitStr)] + "\n"
with open(r"test.txt", "w") as fp:
fp.write(txt)
It looks like if there is no keyword found the index become -1.
So you are avoiding the lines w/o keyword.
I would modify your if by adding the condition as follows:
txt = ""
with open(r"test.txt", 'r') as fp:
for line in fp.readlines():
splitStr = "test"
index = line.find(splitStr)
if index > 0:
txt += line[:index + len(splitStr)] + "\n"
elif index < 0:
txt += line
with open(r"test.txt", "w") as fp:
fp.write(txt)
No need to add \n because the line already contains it.
Your code does not append the line if the splitStr is not defined.
txt = ""
with open(r"test.txt", 'r') as fp:
for line in fp.readlines():
splitStr = "test"
index = line.find(splitStr)
if index != -1:
txt += line[:index + len(splitStr)] + "\n"
else:
txt += line
with open(r"test.txt", "w") as fp:
fp.write(txt)
In my solution I simulate the input file via io.StringIO. Compared to your code my solution remove the else branch and only use one += operater. Also splitStr is set only one time and not on each iteration. This makes the code more clear and reduces possible errore sources.
import io
# simulates a file for this example
the_file = io.StringIO("""my name is test1
my name is
my name is test 2""")
txt = ""
splitStr = "test"
with the_file as fp:
# each line
for line in fp.readlines():
# cut somoething?
if splitStr in line:
# find index
index = line.find(splitStr)
# cut after 'splitStr' and add newline
line = line[:index + len(splitStr)] + "\n"
# append line to output
txt += line
print(txt)
When handling with files in Python 3 it is recommended to use pathlib for that like this.
import pathlib
file_path = pathlib.Path("test.txt")
# read from wile
with file_path.open('r') as fp:
# do something
# write back to the file
with file_path.open('w') as fp:
# do something
Suggestion:
for line in fp.readlines():
i = line.find('test')
if i != -1:
line = line[:i]

can we make a for each in python

i want to make a program that count the letter A in the texts
f = open('text.txt', 'r')
content = f.read()
i = 1
for each a in content:
i = i + 1``
print(i)
The best way to do this particular task is by using the built-in count() function. Then the code becomes:
f = open('text.txt', 'r')
content = f.read()
print(content.count("A"))
I think this is what you want:
with open('text.txt', 'r') as f:
i = 0
for char in f:
if char == 'a':
i += 1
print(f'There are {i} a\'s in the txt file.')
string.count(substring)
content.count("a")

delete empty quotes and pattern before it in python

I have a file as below, whenever there is a key with empty value, I want to delete the key and the empty quotes
My file
<items="20" product="abc" condition="new">
<items="10" product="" condition="new">
<items="50" product="xyz" condition="">
<items="" product="mno" condition="fair">
desired output
<items="20" product="abc" condition="new">
<items="10" condition="new">
<items="50" product="xyz">
<product="mno" condition="fair">
I tried somehting like this, this deleted only the quotes. I want to delete the quotes and the value before "="
f= open('test.txt','r')
A1=f.read()
for i in A1:
if i=="''":
A1.remove(i)
print A1
break
You could use a regular expression:
import re
with open('test.txt','r') as A1:
for i in A1:
print(re.sub('[a-z-]+=\"\" *', '', i))
A possible solution could be:
with open('test.txt','r+') as f:
for line in f:
Line=line[1:len(line)-1]
L=Line.split()
for k in L:
if("" not in k):
f.write(k)
f.write(" ")
You could write a function to pass the lines through:
with open('in_file', 'r') as f:
lines = f.readlines()
def process_line(line):
line = line.split('<')[1].rsplit('>')[0]
valids = [val for val in line.split(' ') if '""' not in val]
line = '<{}>\n'.format(' '.join(valids))
return line
with open('out_file', 'w') as f:
for line in lines:
f.write(process_line(line))
You can use regex,
with open('tmp.txt', 'r') as f_in:
with open('tmp_clean.txt', 'w') as f_outfile:
f_out = csv.writer(f_outfile)
for line in f_in:
line = line.strip()
row = []
if bool(re.search('(.*="")', line)):
line = re.sub('[a-z]+=\"\"', '',line)
row.append(line)
else:
row.append(line)
f_out.writerow(row)

How do I count the number of lines that are full-line comments in python?

I'm trying to create a function that accepts a file as input and prints the number of lines that are full-line comments (i.e. the line begins with #followed by some comments).
For example a file that contains say the following lines should print the result 2:
abc
#some random comment
cde
fgh
#another random comment
So far I tried along the lines of but just not picking up the hash symbol:
infile = open("code.py", "r")
line = infile.readline()
def countHashedLines(filename) :
while line != "" :
hashes = '#'
value = line
print(value) #here you will get all
#if(value == hashes): tried this but just wasn't working
# print("hi")
for line in value:
line = line.split('#', 1)[1]
line = line.rstrip()
print(value)
line = infile.readline()
return()
Thanks in advance,
Jemma
I re-worded a few statements for ease of use (subjective) but this will give you the desired output.
def countHashedLines(lines):
tally = 0
for line in lines:
if line.startswith('#'): tally += 1
return tally
infile = open('code.py', 'r')
all_lines = infile.readlines()
num_hash_nums = countHashedLines(all_lines) # <- 2
infile.close()
...or if you want a compact and clean version of the function...
def countHashedLines(lines):
return len([line for line in lines if line.startswith('#')])
I would pass the file through standard input
import sys
count = 0
for line in sys.stdin: """ Note: you could also open the file and iterate through it"""
if line[0] == '#': """ Every time a line begins with # """
count += 1 """ Increment """
print(count)
Here is another solution that uses regular expressions and will detect comments that have white space in front.
import re
def countFullLineComments(infile) :
count = 0
p = re.compile(r"^\s*#.*$")
for line in infile.readlines():
m = p.match(line)
if m:
count += 1
print(m.group(0))
return count
infile = open("code.py", "r")
print(countFullLineComments(infile))

Can't properly remove line from text file

I have a text file called test.txt, with the following content:
This is a test
I want this line removed
I'm trying to write an algorithm in Python 2 that removes the second line ("I want this line removed") as well as the line break on the first line. I'm trying to output this to a second file called test_2.txt; however, the resulting test_2.txt file is empty, and the first line is not there. Why? Here is my code:
#coding: iso-8859-1
Fil = open("test.txt", "wb")
Fil.write("This is a test" + "\n" + "I want this line removed")
Fil.close()
Fil = open("test.txt", "rb")
Fil_2 = open("test_2.txt", "wb")
number_of_lines = 0
for line in Fil:
if line.find("I want") != 0:
number_of_lines += 1
line_number = 1
for line in Fil:
if line.find("I want") != 0:
if line_number == number_of_lines:
for g in range(0, len(line)):
if g == 0:
a = line[0]
elif g < len(line) - 1:
a += line[g]
Fil_2.write(a)
else:
Fil_2.write(line)
line_number += 1
Fil.close()
Fil_2.close()
You are overly complicating your algorithm. Try this instead:
with open('test.txt') as infile, open('test_2.txt', 'w') as outfile:
for line in infile:
if not line.startswith("I want"):
outfile.write(line.strip())
Remembering that open returns an iterator you can simplify, as well as generalise the solution, by writing it like this.
with open('test.txt') as infile:
first_line = next(infile)
with open('test_2.txt', 'w') as outfile:
outfile.write(first_line.strip())
# both files will be automatically closed at this point

Categories