Reputation: 125
I'm working with a text file that has the following structure:
printer_name:
description = printer_description
library = printer_library
form = printer_form
This structure repeats for every printer in the database.
The desired output of the python script I'm working on would look like this:
'printer_name', 'printer_description', 'printer_library', 'printer_form'
'printer_name', 'printer_description', 'printer_library', 'printer_form'
...and so on for every printer record in the text file...
At this point, I keep running into problems with building the desired output while trying to collect each item into a list object for each record.
Here's the latest version I've been working with:
f = input('Enter file name:')
fh = open(f)
lst = list()
for line in fh:
line = line.strip()
if len(line) == 0: continue
elif line.startswith('description'):
descList = line.split()
description = ' '.join(descList[2:])
lst.append(description)
elif line.startswith('library'):
libList = line.split()
libraryItem = libList[2:]
library = libraryItem[0]
lst = lst.append(library)
elif line.startswith('form'):
formList = line.split()
formItem = (formList[2:])
form = formItem[0]
lst = lst.append(form)
else:
printer = line[:-1]
lst = lst.insert(0, printer)
print(lst)
This script returns Python's attribute error indicating that 'NoneType' object has no attribute 'append'. This appears to be referring to the lst.append(description) statement in my first elif block, however, when I comment out the remaining elif blocks and run the script that way, I am able to produce a single list of description items.
I'm thinking that in order to get a 'list' of lists on my way to getting the desired output, I'll need to situate the print(lst) statement so that it's called for every print record which has been built into its own line, but I've been having trouble with that aspect as well.
Anyone willing and able to take a stab at this puzzle for me?
I would really appreciate it!
Upvotes: 0
Views: 56
Reputation:
method append
return None
, so when you try lst = lst.append(library)
set you variable to None
replace all:
lst = lst.append(library)
lst = lst.insert(0, printer)
to
lst.append(library)
lst.insert(0, printer)
if you need a list
of lines
you can try the logic:
lines = list()
for line in fh:
lst = list()
# You code
lines.append(lst)
Upvotes: 1