HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonMinor

Parse text file function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
textfilefunctionparse

Problem

This method takes a text file of my work schedule and parses it. It works, but is kind of kludgey, and I'm looking for feedback and suggestions. My first attempt at a file parser, and my first look at Python (I have dabbled in Java/Android and JavaScript). I'm hoping that between the pseudocode and the comments it will be clear what is going on.

Pseudocode:

def read_body():
    f = open('file')
    tempList = []
    d = custom data object()
    for line in f:
        if line not empty line:
            if begins with a macron:    #denotes new day in the file
                prepare new/empty data object
                for line in f:
                    split line for whitespace
                    if line not empty line
                        if line is work
                            log it in data object
                        else its another activity
                            if pay value, also log it
            elif begins with an equal sign: #denotes end of day
    else:
        clean up
    f.close()


Full Code (it works):

```
macron = '¯'
equalSign = '='
underscore = '_'

def read_body(path, month_year):
'''Reads schedule detail text file and generates pairing data objects for each work day.
path: file to open 'monthYEAR.txt'
date: MonthYEAREMPNO (month, year, employee number)
from file header
'''
f = open(path)
tempList = []
d = WorkDay()
for line in f:
tempList = line.rsplit()
if len(tempList) > 0:
if macron in tempList[0]: #begin work day
#prepare new data object
d.clear()
d.month_year(month_year)
for line in f:
tempList = line.rsplit()
if len(tempList) > 0:
if isWorkingDay(tempList[0]): #parse tempList[1] date block MM/dd/YYYY
d.activity_name(tempList[0])

Solution

As a recommendation for readability i suggest you replace

if len(tempList) > 0:


with

if tempList:


as the Empty List resolves to False.

It's also recommended to use the "with statement" when dealing with files to avoid errors.

with open('file') as f:
   ...


This will free any locks on the filesystem once this block is exited.

Code Snippets

if len(tempList) > 0:
if tempList:
with open('file') as f:
   ...

Context

StackExchange Code Review Q#58924, answer score: 4

Revisions (0)

No revisions yet.