Kehlin Swain
Kehlin Swain

Reputation: 481

Text File Reading and Structuring data

Text File

• I.D.: AN000015544 
DESCRIPTION: 6 1/2 DIGIT DIGITAL MULTIMETER 
MANUFACTURER: HEWLETT-PACKARDMODEL NUM.: 34401A CALIBRATION - DUE DATE:6/1/2016 SERIAL NUMBER: MY45027398 
• I.D.: AN000016955 
DESCRIPTION: TEMPERATURE CALIBRATOR 
MANUFACTURER: FLUKE MODEL NUM.: 724 CALIBRATION - DUE DATE:6/1/2016 SERIAL NUMBER: 1189063 
• I.D.: AN000017259 
DESCRIPTION: TRUE RMS MULTIMETER 
MANUFACTURER: AGILENT MODEL NUM.: U1253A CALIBRATION - DUE DATE:6/1/2016 SERIAL NUMBER: MY49420076 

Objective

To read the text file and save the ID number and Serial number of each part into the part_data data structure.

Data Structure

part_data = {'ID': [],
               'Serial Number': []}

Code

with open("textfile", 'r') as part_info:
    lineArray = part_info.read().split('\n')
    print(lineArray)
    if "• I.D.: AN000015544 " in lineArray:
        print("I have found the first line")
        ID = [s for s in lineArray if "AN" in s]
        print(ID[0])

My code isn't finding the I.D: or the serial number value. I know it is wrong I was trying to use the method I got from this website Text File Reading and Printing Data for parsing the data. Can anyone move me in the right direction for collecting the values?

Update

This solution works with python 2.7.9 not 3.4, thanks to domino - https://stackoverflow.com/users/209361/domino:

with open("textfile", 'r') as part_info:
lineArray = part_info.readlines()
for line in lineArray:
    if "I.D.:" in line:
        ID = line.split(':')[1]
        print ID.strip()

However when I initially asked the question I was using python 3.4, and the solution did not work properly.

Does anyone understand why it doesn't work python 3.4? Thank You!

Upvotes: 0

Views: 221

Answers (2)

Kyle Roux
Kyle Roux

Reputation: 746

It won't work in python3 because in python3 print is a function

It should end

print(ID.strip())

Upvotes: 1

domino
domino

Reputation: 2165

This should print out all your ID's. I think it should move you in the right direction.

with open("textfile", 'r') as part_info:
    lineArray = part_info.readlines()
    for line in lineArray:
        if "I.D.:" in line:
            ID = line.split(':')[1]
            print ID.strip()

Upvotes: 1

Related Questions