Enumerating, and printing lines in Python. - python-3.x

Okay, I am building a little program that will help single out Nmap results:
#Python3.7.x
#
#
#
#report=input('Name of the file of Nmap Scan:\n')
#target_ip=input('Which target is the report needed on?:\n')
report = "ScanTest.txt"
target_ip = "10.10.100.1"
begins = "Nmap scan report for"
fhand = open(report,'r')
beginsend = "Network Distance:"
for num1,line in enumerate(fhand, 1):
line = line.rstrip()
if line.startswith(begins) and line.endswith(target_ip):
print(num1)
for num2,line in enumerate(fhand, 1):
line = line.rstrip()
if line.startswith(beginsend):
print(num2)
In my what im trying to do is get the first part of the scan results "target_ip" and with that i hope i can read the lines from there until there is a break in the line of the txt.
What this code does for me now is just get me the line number where i want to start.
In the second part of the code I tried getting the number of line for the last bit of text that i need. But it wont print. Im not sure if im going about this the right way or im not looking hard enough.
In short find my line and print until there is a break in the text.

The first loop exhausts all the lines in the file. When the second loop tries to run, there are no more lines to read and the loop exits immediately.
If you want the first loop to stop when it finds a matching line and allow the second loop to read the remaining lines, you can add a break statement in the if.
start_pattern = 'hello there'
end_pattern = 'goodblye now'
print_flag = False
with open('somefile.txt') as file:
for line in file:
if start_pattern in line:
print_flag = True
if print_flag:
print line
if end_pattern in line:
break

Related

to print the next line using pythons loop

i matched a line using regex and now i wanna to print the line next to all the matched line.
import re
file = open(input("Input-file name : ") , "r")
fi = file.readlines()
f=file.readline()
pat=r'^[^\n(E|P):]:\s[EXINTF_DATA\d]\d'
for line in fi:
if re.match(r'^[^\n(E|P):]:\s[EXINTF_DATA\d]\d',line):
print(line.strip())#all the 'Startpoint:'s from the file is getting printed
s=line.strip()
for s in range(len(fi)-1):
if 'input port clocked by CLK' in fi:
print(s.strip())
i also tried last for loop part like this,
for s in range(len(fi)-1):
l=line.startswith('input port clocked by CLK')
print(l)#but this loop was running continoulsy
am trying to print till the string found after printing the next line. am also attaching my text file and how it looks like
am a very beginner in python. can someone help me on this, please.

Python: Reading line with 'readline()' function and appending to a list

My code:
In my file i have these numbers in a list
charge_account = ['4654145', '9658115', '5658845', '5658045', '6181531', '2134874', '5964554']
I am reading the file with a function, appending it to a list and then returning the list:
import os
os.system('cls')
def fileReader():
contentList = []
with open('charge_accounts.txt','r') as f:
line = f.readline().rstrip('\n')
while line !="":
line = f.readline().rstrip(' \n')
contentList.append(line)
# print(contentList)
# print(len(contentList))
#contentList = contentList[:-1]
print(contentList)
return contentList
Now my question is, when i read all the file content and append them to my list, i am getting an extra blank string at the end of the list.
output:
['4654145', '9658115', '5658845', '5658045', '6181531', '2134874', '5964554', '']
Now i have solved it by using slicing (as i commented them out) but i still have not figured out why i am getting the ' ' in the end of the list. i tried filtering it out but noting happens. i have checked if it there is an extra line in the end of the file but what am i doing wrong ?
There are a couple of things. You are reading the file line by line in the while loop. This means that after the last line is read, the while condition is still true so you read an extra line (which is empty) but still added to your list.
But you don't need a while loop: use lines = f.readlines(). It will read the whole file in a list, and you almost have the list you are aiming for. Almost, because you need to strip each element:
def fileReader():
with open('charge_accounts.txt','r') as f:
lines = f.readlines()
return [line.strip() for line in lines]
print(fileReader())
while line !="":
contentList.append(line)
line = f.readline().rstrip(' \n')
print(contentList)
I realized i had to append the while loop primer into the list which i read before the loop started. content.append(line) had to be the first statement in the while loop. This solves the blank entry in the end of list, which in hindsight i realize means that i skipped the first readline value.

IndexError: list index out of range, but list length OK

New to programming, looking for a deeper understanding on whats happening.
Goal: open a file and print the first 10 lines. (similar to head command)
Code:
with open('file') as f:
for i in range(0,10):
print([line.strip('\n') for line in f][i])
Result: prints first line fine, then returns the out of range error
File: Is a simple text file with 20 lines, no more than 50 chars per line
FYI - Removed range line and printed both type(list) and length(20). Printed specific indexes without issue (unless >1 in a row)
Able to get the desired result with different code, but trying to improve using with/as
You can actually iterate over a file. Which is what you should be doing here.
with open('file') as f:
for i, line in enumerate(file, start=1):
# Get out of the loop if we hit 10 lines
if i >= 10:
break
# Line already has a '\n' at the end
print(line, end='')
The reason that your code is failing is because of your list comprehension:
[line.strip('\n') for line in f]
The first time through your loop that consumes all of the lines in your file. Now your file has no more lines, so the next time through it creates a list of all the lines in your file and tries to get the [1]st element. But that doesn't exist because there are no lines at the end of your file.
If you wanted to keep your code mostly as-is you could do
lines = [line.rstrip('\n') for line in f]
for i in range(10):
print(lines[i])
But that's also silly, because you could just do
lines = f.readlines()
But that's also silly if you just want up to the 10th line, because you could do this:
with open('file') as f:
print('\n'.join(f.readlines()[:10]))
Some further explanation:
The shortest and worst way you could fix your code is by adding one line of code:
with open('file') as f:
for i in range(0,10):
f.seek(0) # Add this line
print([line.strip('\n') for line in f][i])
Now your code will work - but this is a horrible way to get your code to work. The reason that your code isn't working the way you expect in the first place is that files are consumable iterators. That means that when you read from them eventually you run out of things to read. Here's a simple example:
import io
file = io.StringIO('''
This is is a file
It has some lines
okay, only three.
'''.strip())
for line in file:
print(file.tell(), repr(line))
This outputs
18 'This is is a file\n'
36 'It has some lines\n'
53 'okay, only three.'
Now if you try to read from the file:
print(file.read())
You'll see that it doesn't output anything. That's because you've "consumed" the file. I mean obviously it's still on disk, but the iterator has reached the end of the file. But as shown, you can seek in the file.
print(file.tell())
file.seek(0)
print(file.tell())
print(file.read())
And you'll see your entire file printed. But what about those other positions?
file.seek(36)
print(file.read()) # => okay, only three.
As a side note, you can also specify how much to read:
file.seek(36)
print(file.read(4)) # => okay
print(file.tell()) # => 40
So when we read from a file or iterate over it we consume the iterator and get to the end of the file. Let's put your new tools to work and go back to your original code and explore what's happening.
with open('file') as f:
print(f.tell())
lines = [line.rstrip('\n') for line in f]
print(f.tell())
print(len([line for line in f]))
print(lines)
You'll see that you're at a different location in the file. And the second list comprehension produces an empty list. That's because when a list comprehension is evaluated it executes immediately. So when you do this:
for i in range(10):
print([line.strip('\n') for line in f][i])
What you're doing the first time, i = 0 and then the list comprehension reads to the end of the file. Now it takes the [0]th element of the list, or the first line in the file. But your file iterator is at the end of the file.
So now we get back to the beginning of the list and i = 1. Now we iterate to the end of the file, but we're already at the end so there are no lines to read, and we've got an empty list [] that we try to get the [0]th element of. But there's nothing there. So we get an IndexError.
List comprehensions can be useful, but when you're beginning it's usually much easier to write a for loop and then turn it into a list comprehension. So you might write something like this:
with open('file') as f:
for i, line in enumerate(file, start=10):
if i < 10:
print(line.rstrip())
Now, we shouldn't print inside a list comprehension, so instead we'll collect everything. We start out by putting what we want:
[line.rstrip()
Now add the for bit:
[line.rstrip() for i, line in enumerate(f)
And finally add the filter and our closing brace:
[line.rstrip() for i, line in enumerate(f) if i < 10]
For more on list comprehensions, this is a fantastic resource: http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

Using python to remove nearly identical lines in txt file, with the exception of first and last lines

Here is a snippet from a text file I am working on.
http://pastebin.com/4Uba5i4P
I would like to use python to detect those big repeating "~ Move" lines (Which are not identical except for the "~ Move" part.), and remove all but the first and last of those lines.
How I would I start to go about this?
You could read the file line by line like this:
`## Open the file with read only permit
f = open('myTextFile.txt')
## Read the first line
line = f.readline()
## If the file is not empty keep reading line one at a time #
# till the file is empty while line: print line
line = f.readline() f.close()`
With this you could then edit this sample to test each line using a regex like this:
`if line.find("~Move") == -1:
Break;
Else:
Line=Line [5:-1]`
Though this assumes that the ~Move is all at the beginning of the line. Hope this helps, if not leave a comment and I'll try and help.

Using for loop to strip white space and resetting the pointer prior to reading a file

I'm using Pycharm and have been very happy so far. However, today I ran into a issue that I can't figure out or explain. The code will prompt the user for an input file. The file is a .txt file that contains lines of words. After the user provides the filename, the program will open it, remove white spaces at the end of the lines and print the contents of the file. (lots_of_words.txt = example)
INPUT
print(lots_of_words.txt)
OUTPUT
Programming is fun and will save the world from errors! ....
Here is the part of the code that is causing the confusion:
user_input = input('Enter the file name: ')
open_file = open(user_input)
for line in open_file:
line = line.rstrip()
read_file = open_file.read()
print(read_file)
OUTPUT
Process finished with exit code 0
Now by just removing the for loop with string.rstrip(), the text file prints fine:
INPUT
user_input = input('Enter the file name: ')
open_file = open(user_input)
# Removed for loop
read_file = open_file.read()
print(read_file)
OUTPUT
Programming is fun and will save the world from errors! ....
I'm using python 3.4 with Pycharm IDE. I realize that the script completed fine without errors, but why won't it print the final variable? I'm sure this is a simple answer, but I can't figure it out.
Running the same code in Python 2.7, prints fine even with string.rstrip().
It has nothing to do with PyCharm.
Your for moves the pointer to the end of the file. To use open_file again, use seek(0), before printing.
open_file = open(user_input)
for line in open_file:
line = line.rstrip()
open_file.seek(0)
read_file = open_file.read()
print(read_file)
Not the most efficient solution though (if efficiency matters in given situation), since you read all the lines twice. You can either store each line after reading it (as suggested in the other answer), or print each line after striping it.
Also, rstrip() will remove whitespaces at the end of the string, but not '\n'.
Irrelevant: You should use with open() as.. : instead of open() since it closes the file automatically.
Iterating over your file object in the for loop will consume it, so there will be nothing left to read, you're simply discarding all lines.
If you want to strip all whitespace from all lines, you could use:
user_input = input('Enter the file name: ')
open_file = open(user_input)
lines = []
for line in open_file:
lines.append(line.rstrip())
print(''.join(lines))
or even shorter:
print(''.join(line.rstrip() for line in open_file))

Resources