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

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')

Related

python text file parse and print

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

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()

Why aren't the lists populating in this code?

I wrote this code for class and cannot figure out why my lists are not populating with any values. I've tried using a debugger and still can't figure out why it won't work. Any ideas? Also... I know for loops would have made more sense, but I needed to use while loops for the assignment.
__author__ = 'Ethan'
#This program reads in a file from the user which contains lines of
def mileage():
filename = input("Please enter the file name: ")
file = open(filename,"r")
line_list = []
num_lines = sum(1 for line in file)
line_counter = 0
while line_counter <= num_lines:
line = file.readline()
line_items = line.split()
line_list.append(line_items)
line_counter += 1
current_index_pos = 0
while current_index_pos <= num_lines:
current_item = line_list[current_index_pos]
print("Leg",current_index_pos + 1,"---", current_item[0]/current_item[1],"miles/gallon")
current_index_pos += 1
mileage()
This reads to the end of the file
num_lines = sum(1 for line in file)
so there are no lines left to read when you get here
line = file.readline()
Better to structure the code like this
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
line_items = line.split()
line_list.append(line_items)
# after the loop line_counter has counted the lines
or even (if you don't need line_counter)
with open(filename, "r") as fin:
line_list = [line.split() for line in fin]
More advanced would be to use a generator expression or do everything in a single loop to avoid needing to read the whole file into memory at once
def mileage():
filename = input("Please enter the file name: ")
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
current_item = line.split()
print("Leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")

Deleting a complete line if an entry in the line is not present a list

I am trying to parse every line in list.txt and if any of the change(number) is not present in change_list, delete that whole entry (not just that number) and create an new file OUTPUT.txt with the remaining numbers.
In the below example 350166 is not present in change_list, so the whole line "350882 348521 350166" is removed and only the remaining ones are added to output.txt.
For some reason I dont seem to get the desired outupt. Can anyone point where is it going wrong?
change_list=[]
def changecheck(change) :
changelist=['355199','352470','346917','350882','348521']
if change in changelist:
return 1
else:
return 0
with open('list.txt', 'r') as f:
for line in f :
line=line.strip()
change_line = line
print "change_line"
print change_line
for element in change_line:
change_list = element.split(' ')
for changeid in change_list:
print "changeid"
print changeid
returnVal = changecheck('changeId')
if returnVal == 1:
#write the whole line to a new file
with open('output.txt', 'r') as f:
f.writelines(element)
files:
list.txt
350882 348521 350166
346917 352470
355199
OUTPUT.txt
346917 352470
355199
Make your changecheck a set, and then build a generator over the input splitting it up into separate numbers, and only include lines in the file where all numbers on the line are in the changecheck..., eg:
changelist = {'355199','352470','346917','350882','348521'}
with open('input') as fin, open('output', 'w') as fout:
lines = (line.split() for line in fin)
valid = (' '.join(line) + '\n' for line in lines if all(el in changelist for el in line))
fout.writelines(valid)

Categories

Resources