python text file parse and print - python

I have a text file with 300 lines.
I am looking for a word "ABC" in each line
If this word is found i want to print the line before it was found and then the next X lines.
This is the code i have so far but i don't know how to print based on given problem statement.
path = ('C:\\Users\\40081\\PycharmProjects\\datalog_parsing')
count2=1
count1=1
num_lines = open('BBCnt123.txt').read().count('\n')
print (num_lines)
count2=count1
while count2<=num_lines:
file_name = open("BBCnt123.txt", 'r+')
f= open('BBCnt1234' + '.txt', 'w+')
for line_no, line in enumerate (file_name):
line=f.readlines()
if "BBCnt" in line:
f.writelines((line[count2-1]) )
count2= count2+1
file_name.close()
f.close()

with open("file.txt","r") as f:
lines=f.readlines()
[print(lines[c-1]+lines[c:c+X]) for c,e in enumerate(lines) if "ABC" in e]
Try this list comprehension

Related

Delete a certain line in text file if user input string matches

If that string input by User exists in text file, the program should find/return line number in text file and print the line number
kw is the user input btw
some code for reference:
def DELITEM():
kw = Dele.get()
with open('notify.txt') as f:
if kw in f.read:
print('the number of the line kw is in')
I guess you could do something like:
with open('notify.txt', 'r') as f:
for num, line in enumerate(f):
if kw==line:
print(num)
Here enumerate() adds a counter to the file that allows you to identify lines.
you could loop through the lines until you find it with readlines
DELITEM():
kw = Dele.get()
with open('notify.txt', 'r') as f:
if kw in f.read:
lines = f.readlines()
for i in range(len(lines)):
if kw in lines[i]:
print("The line is",i)
break
To delete the line from the text file, on way would be to delete the line in the list then write the lines back onto the file. So something like this
del lines[i]
then have another with where you write
with open('notify.txt', 'w') as f:
for line in lines:
f.write(line + '\n')
so putting this altogether you have
DELITEM():
lines = []
kw = Dele.get()
with open('notify.txt', 'r') as f:
if kw in f.read:
lines = f.readlines()
for i in range(len(lines)):
if kw in lines[i]:
print("The line is",i)
del lines[i]
break
with open('notify.txt', 'w') as f:
for line in lines:
f.write(line + '\n')

How to print the word from a file in python

i tried using the .strip() method which give me the line
f = open("myFile.txt")#this open myfile
for i in range(500): # print 500 character
line = f.readline().strip()
print(line)
my expected result is
"faowijfaoijfaoiwjfioawjfafawjfaoiwjfawofjafw"
You can do this.
with open("myFile.txt") as f:
chars_100 = f.read(100)
print (chars_100)

I need to search a string in data file. but the string is written in another file

I have key words to be search in one file let say abc.txt and in another file I have my data, def.txt.
I want a code in python to find key words written in abc.txt, in def.txt and if present, print those line in a new file.
Thank you.
I tried writing a code but it didn't work.
following is the code I write.
f = open('/home/vivek/Documents/abc.txt')
f1 = open('output.txt', 'a')
f2 = open('/home/vivek/Documents/def.txt', 'r')
# doIHaveToCopyTheLine=False
for line in f.readlines():
if f2 in line:
f1.write(line)
f1.close()
f.close()
f2.close()
Load the keywords into a list then you can check the other file line-by-line, and write to outfile as you find keywords in the line.
with open('/path/to/keywords.txt') as f:
keywords = set(line.strip() for line in f) # assuming words are separated by line
with open('/path/to/search_me.txt') as f, open('/path/to/outfile.txt', 'w') as outfile:
for line in f:
if any(kw in line for kw in keywords):
outfile.write(line)
You should record all the words in abc.txt use a set and then search them in def.txt
word_set = set()
with open('/home/vivek/Documents/abc.txt') as f:
for line in f:
word_set.add(line.strip())
f1 = open('output.txt', 'a')
with open('/home/vivek/Documents/def.txt') as f:
for line in f:
find = False
for word in word_set:
if word in line:
find = True
break
if find:
f1.write(line)
f1.close()
You can try this code:
with open("keyword.txt", "r") as keyword_file:
keywords = keyword_file.read().strip()
keywords = keywords.split()
with open("data.txt", "r") as data_file, open("output.txt", "w") as output_file:
for line in data_file.readlines():
line = line.strip()
for word in keywords:
if line.find(word) != -1:
print line
output_file.writelines(line + '\n')
break
In addition to sytech's answer you may try this:
with open('def.txt') as kw_obj, open('abc.txt') as in_obj:
keywords = set(kw_obj.read().split())
in_lines = in_obj.readlines()
match_lines = [line for keyword in keywords for line in in_lines if keyword in line]
if match_lines:
with open('out.txt', 'w') as out:
out.write(''.join(match_lines))

Writing before specific line python

i have this piece of code:
asm = open(infile)
asmw = open(outfile, "w")
shutil.copyfile(infile, outfile)
for x in range(0, 8):
xorreg.append("xor " + reg[x] + ", " + reg[x])
for line in asm:
if any(s in line for s in xorreg):
found += line.count(xorreg[x])
print line
i want to write some text lines in the file right before "line" (the one printed)
how can i do that?
Thanks
This script appends to every lien containing the string Gandalf a new string The greatest wizard of all times was:
# show what's in the file
with open("some_file.txt", 'r') as f:
print f.read()
new_content = []
with open("some_file.txt", "r") as asmr:
for line in asmr.readlines():
if "Gandalf" in line:
# we have a match,we want something but we before that...
new_content += "The greatest wizard of all times was:"
new_content += line
# write the file with the new content
with open("some_file.txt", "w") as asmw:
asmw.writelines(new_content)
# show what's in the file now
with open("some_file.txt", 'r') as f:
print f.read()

Match the last word and delete the entire line

Input.txt File
12626232 : Bookmarks
1321121:
126262
Here 126262: can be anything text or digit, so basically will search for last word is : (colon) and delete the entire line
Output.txt File
12626232 : Bookmarks
My Code:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not ":" in line:
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
Problem: When I match with : it remove the entire line, but I just want to check if it is exist in the end of line and if it is end of the line then only remove the entire line.
Any suggestion will be appreciated. Thanks.
I saw as following but not sure how to use it in here
a = "abc here we go:"
print a[:-1]
I believe with this you should be able to achieve what you want.
with open(fname) as f:
lines = f.readlines()
for line in lines:
if not line.strip().endswith(':'):
print line
Here fname is the variable pointing to the file location.
You were almost there with your function. You were checking if : appears anywhere in the line, when you need to check if the line ends with it:
def function_example():
fn = 'input.txt'
f = open(fn)
output = []
for line in f:
if not line.strip().endswith(":"): # This is what you were missing
output.append(line)
f.close()
f = open(fn, 'w')
f.writelines(output)
f.close()
You could have also done if not line.strip()[:-1] == ':':, but endswith() is better suited for your use case.
Here is a compact way to do what you are doing above:
def function_example(infile, outfile, limiter=':'):
''' Filters all lines in :infile: that end in :limiter:
and writes the remaining lines to :outfile: '''
with open(infile) as in, open(outfile,'w') as out:
for line in in:
if not line.strip().endswith(limiter):
out.write(line)
The with statement creates a context and automatically closes files when the block ends.
To search if the last letter is : Do following
if line.strip().endswith(':'):
...Do Something...
You can use a regular expression
import re
#Something end with ':'
regex = re.compile('.(:+)')
new_lines = []
file_name = "path_to_file"
with open(file_name) as _file:
lines = _file.readlines()
new_lines = [line for line in lines if regex.search(line.strip())]
with open(file_name, "w") as _file:
_file.writelines(new_lines)

Categories

Resources