2

I am trying to parse/process some information from a text file using Python. This file contains names, employee numbers and other data. I do not know the names or employee numbers ahead of time. I do know that after the names there is the text: "Per End" and before the employee number there is the text: "File:". I can find these items using the .find() method. But, how do I ask Python to look at the information that comes before or after "Per End" and "File:"? In this specific case the output should be the name and employee number.

The text looks like this:

SMITH, John
Per End: 12/10/2016
File:
002013
Dept:
000400
Rate:10384 60

My code is thus:

file = open("Register.txt", "rt")
lines = file.readlines()
file.close()

countPer = 0
for line in lines:
    line = line.strip()
    print (line)
    if line.find('Per End') != -1:
        countPer += 1
print ("Per End #'s: ", countPer)
1
  • enumerate helps you to access line and its index at the same time Commented Jun 20, 2017 at 16:19

2 Answers 2

1
file = open("Register.txt", "rt")
lines = file.readlines()
file.close()

for indx, line in enumerate(lines):
    line = line.strip()
    print (line)
    if line.find('Per End') != -1:
        print lines[indx-1].strip()
    if line.find('File:') != -1:
        print lines[indx+1].strip()

enumerate(lines) gives access to indices and line as well, there by you can access previous and next lines as well

here is my stdout directly ran in python shell:

>>> file = open("r.txt", "rt")
>>> lines  = file.readlines()
>>> file.close()
>>> lines
['SMITH, John\n', 'Per End: 12/10/2016\n', 'File:\n', '002013\n', 'Dept:\n', '000400\n', 'Rate:10384 60\n']

>>> for indx, line in enumerate(lines):
...     line = line.strip()
...     if line.find('Per End') != -1:
...        print lines[indx-1].strip()
...     if line.find('File:') != -1:
...        print lines[indx+1].strip()

SMITH, John
002013
Sign up to request clarification or add additional context in comments.

13 Comments

I try this code and I get this error: TypeError: 'builtin_function_or_method' object has no attribute 'getitem' This will need to run off of a text file with multiple employees
yes, this did work for me for a text file with multiple employees. I created a sample text file based on your sample data in the question
Thanks. But how can I get around the error? " TypeError: 'builtin_function_or_method' object has no attribute 'getitem' "
I found my mistake, corrected it, then received this error in it's stead: " print line[indx+1].strip() Per End: 12/10/2016 IndexError: string index out of range" The code is exact to yours at this point. Not sure how to get around it.
how does your lines list look like? can you print it like I did it in my shell and put it here?
|
0

Here is how I would do it.

First, some test data.

test = """SMITH, John\n
Per End: 12/10/2016\n
File:\n
002013\n
Dept:\n
000400\n
Rate:10384 60\n"""

text = [line for line in test.splitlines(keepends=False) if line != ""]

Now for the real answer.

count_per, count_num = 0, 0

Using enumerate on an iterable gives you an index automagically.

for idx, line in enumerate(text):

    # Just test whether what you're looking for is in the `str`

    if 'Per End' in line:
        print(text[idx - 1]) # access the full set of lines with idx
        count_per += 1
    if 'File:' in line:
        print(text[idx + 1])
        count_num += 1

print("Per Ends = {}".format(count_per))
print("Files = {}".format(count_num))

yields for me:

SMITH, John
002013
Per Ends = 1
Files = 1

2 Comments

This works well but I will need to pull in data from a text file that includes multiple employees. will this allow me to do that and print this result for each time it finds the specified strings?
sure. just change enumerate(text) to enumerate(lines) with your original lines being read in from a file. I just like to provide test data so that others can follow despite not having your original file - I'm too well trained to have tests :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.