Reading a line's number in a file - python

Currently I have:
for line in f:
if line == promble:
print("check")
I want to make the program print the line after the line I have selected. Help.

If you want to test a line in a file, and if it matches print the next line in the file, try:
selected = False
for line in f:
if selected:
print line
selected = False
if line == promble:
selected = True

Use enumerate
for index,line in enumerate(f):
if line == promble:
print f[index+1]

Your file object f has an __iter__ attribute, so you can apply next to get the next item in your loop:
for line in f:
if line == promble:
print(next(f)) # prints next line after the current one
If f is neither a file object nor an iterator, you can call iter on f to make one:
it = iter(f)
for line in it:
if line == promble:
print(next(it))
If f was already an iterator, calling iter on f will return f again, so it still works fine.

Related

How to delete specific line in text file?

I'm making a joke program that has a text file storing jokes. On program load, it grabs all the lines from the file and assigns them to a jokes list Everything but the remove joke function is working. Whenever you call remove joke, it ends up re-writing every line in the text file to an empty string instead of the selected line
When running this function, it does remove the joke from the jokes list properly
def remove_joke():
for i in range(len(jokes)):
print(f"{i}\t{jokes[i]}")
remove_index = int(input("Enter the number of the joke you want to remove:\t"))
with open("jokes.txt", "r") as f:
lines = f.readlines()
with open("jokes.txt", "w") as f:
for line in lines:
print(line)
if line == jokes[remove_index]:
f.write("")
jokes.remove(jokes[remove_index])
Instead of
if line == jokes[remove_index]:
f.write("")
you want:
if line != jokes[remove_index]:
f.write(line+'\n')
Or even:
if line != jokes[remove_index]:
print(line, file=f)

Unable to move to second function after the result of the first

Program Goal: Search a defined yamlfile (scan_dcn.yaml) and return all lines matching the search criteria as defined in the function_search_search_key() and function_search_event_type() functions.
Input File - scan_dcn.yaml:
search_dict:
[
{search_key: ["Failed to Process the file"],
event_type: "evttyp_repl_dcn_error",
event_description: "Failure to process DCN file",
priority: 50,
scan_interval: 1,
remove_dups: True,
category: "dcn",
context_begin: 0,
context_end: 1,
reportable: False,
offset: 0
},
Problem:
My program will return function_search_search_key() but will not proceed to function_search_event_type().
I would think that my problem is that I have no logic to proceed to the second function after the completion of the first.
Do I need to return a value in each function to proceed?
Python Source Code
yamlfile = open('scan_dcn.yaml', 'r')
def function_search_search_key():
search_search_key = ['{search_key:']
for line in yamlfile.readlines():
for word in search_search_key:
if word in line:
print(line)
def function_search_event_type():
search_event_type = ['event_type:']
for line in yamlfile.readlines():
for word in search_event_type:
if word in line:
print(line)
def main():
function_search_search_key()
function_search_event_type()
main()
In your first function you read the whole file with readlines. When you use readlines again in your second function you're already at the end of the file and there is no more data to read, so the for loop is not even entered.
But there's no need to read the file again for every function. Read the file outside of the functions and put it in a list. Then add a parameter to each of those functions that takes this list. In the function you can loop over the list.
def function_search_search_key(lines):
search_search_key = ['{search_key:']
for line in lines:
for word in search_search_key:
if word in line:
print(line)
def function_search_event_type(lines):
search_event_type = ['event_type:']
for line in lines:
for word in search_event_type:
if word in line:
print(line)
def main():
with open('scan_dcn.yaml', 'r') as yamlfile:
lines = yamlfile.readlines()
function_search_search_key(lines)
function_search_event_type(lines)
if __name__ = '__main__':
main()
If you ever need to change the name of the file you can do it in one place. If you open and read the file in every single function you would have to change all occurrances of the file name.
Your second function is being entered. It must if the call above it has finished.
You aren't seeing anything printed because you're attempting to loop though the same file more than once. Once you've read the file, it's exhausted. You can just re-read the file as a simple fix:
def function_search_search_key():
with open('scan_dcn.yaml', 'r') as yamlfile:
search_search_key = ['{search_key:']
for line in yamlfile.readlines():
for word in search_search_key:
if word in line:
print(line)
def function_search_event_type():
with open('scan_dcn.yaml', 'r') as yamlfile: # Read the file again
search_event_type = ['event_type:']
for line in yamlfile.readlines():
for word in search_event_type:
if word in line:
print(line)
You can read a file descriptor only once (if you don't seek to start), so you may open your file in each function
def function_search_search_key():
search_search_key = ['{search_key:']
with open('scan_dcn.yaml') as fic:
for line in fic:
for word in search_search_key:
if word in line:
print(line)
def function_search_event_type():
search_event_type = ['event_type:']
with open('scan_dcn.yaml') as fic:
for line in fic:
for word in search_event_type:
if word in line:
print(line)

pyqt Qtextbrowser update

def sort_domain():
if self.cb1.isChecked():
for line in f:
line= line.strip()
if line.endswith('.com') is True:
self.textBrowser.append(line)
else:
pass
elif not self.cb1.isChecked() and not self.cb2.isChecked():
for line in f:
line=line.strip()
self.textBrowser.append(line)
if self.cb2.isChecked():
for line in f:
line= line.strip()
if line.endswith('.net') is True:
self.textBrowser.append(line)
else:
pass
elif not self.cb1.isChecked() and not self.cb2.isChecked():
for line in f:
line=line.strip()
self.textBrowser.append(line)
self.btn2.clicked.connect(sort_domain)
If I checked cb1 and cb2 ((checkbox1 and chekbok2))
the results are all domains with extension .com only.
What is the correct way to write a function to show all Domains when you press the chekBox1 ".com" and chekBox2 ".net"?
Your implementation is not really efficient: it reads the contents of the file more than once. And this is also the issue of your program. After the first for-loop the file object points to the end of the file and to make it work you'd have to seek to the start again: f.seek(0)

Python Function return value for 1 iteration only

I do have following code where I am its doing following thing.
Parsing Whole file and checking for patter in each line. If the pattern exists, it should return that pattern to main function and print the value.
Issue: The function is only returning 1st pattern and do not check for same pattern into multiple lines.
code:
import re
import sys
import os
def find_pattern(file):
with open(file) as fp:
for line in fp:
if "abc" in line:
return line
else:
continue
def check(file):
return_list = []
data=find_pattern(file)
if data != None:
return_list.append(data)
if not data:
return "working"
else:
return return_list
if __name__== '__main__':
file = sys.argv[1]
print check(file)
If the file has multiple line containing abc, it will print only 1st line and skip other lines. I want to print all lines that contains abc.
Sample file
sdfdsffdabcafsfse
asasssadfsdadsadsaddsadadabc
asfasfdsafdfabc
output with above code:
sdfdsffdabcafsfse
You are prematurely returning from the function on this line:
return line
Which means you exit the function and the loop ceases to iterate assoon as the first instance is found.
Consider something like this instead, where you capture and return all matches:
def find_pattern(file):
out = []
with open(file) as fp:
for line in fp:
if "abc" in line:
out.append(line)
else:
continue
return out
Alternatively, you can manage this in a single, simple list comprehension:
def find_pattern(file):
with open(file) as fp:
return [line for line in fp if "abc" in line]

Python 3, increment iterator

I am processing a file line by line. Each line is checked, whether it contains a given text. Then, the next line needs to be assigned to the variable
i_line = iter(file)
for i_line in file:
if text in i_line:
#Go to the next line
line = next(i_line, None) #A problem
break
How to increment iterator i_line so as to point to the next line of the file? Both constructions do not work for me
next(i_line, None)
i_line.next()
Just do next(f).
Something like
>>> with open('testFile.txt', 'r') as f:
for line in f:
if 'cat' in line:
final_string = next(f)
So, for an input text file of
My Name is ABC.
I am a male.
My pet is a cat.
It's name is Ronald.
I hate rats.
The above code gives
>>> final_string
"It's name is Ronald.\n"
Use line = file.next() instead of line = next(i_line, None).
Here's a way of processing a file with next().
with open(filename) as file:
line = next(file, None)
while line:
print(line.strip())
line=next(file, None)
Using both the for line in file iterator and next would print every other line:
with open(filename) as file:
for line in file:
print(line.strip())
line = next(file,None)

Categories