简体   繁体   中英

How do i check/validate existing file with my requirement in python

Suppose I have a file named abc.txt with contents FirstName, Last name, Age, gender

Jack, Hugman, 22, M
Joe, Zareil, 32, M
Ashely, Timberlake, 28, F

Now my requirement is this that I only need FirstName, LastName, and age only. So how do i validate/check my requirement with a file. These three field i would be using in my class objects

class A:

def __init__(self, fname, lname, age):
    self.fname = fname
    self.lname = lname
    self.age = age

fp = open("abc","r")

for lines in fp:
    temp = lines.split(",")
    print temp

this is what uptil i have done. what should i do to check/validate?

A simple way is using exceptions: Basically specify what you expect from the file, parse it assuming that everything is in there. If an assertion triggers something was off.

For example you could do:

a = A(temp[0], temp[1], int(temp[2])

you can split like this

for lines in fp:
    temp = lines.split(",")[:-1]
    print temp

You can just ignore the fourth field.

class A:
    def __init__(self, fname, lname, age):
        self.fname = fname
        self.lname = lname
        self.age = age

    def __str__(self):
        return "fname={}, lname={}, age={}".format(self.fname, self.lname, self.age)

with open("abc.txt") as f:
    for line in f:
        fname, lname, age = [g.strip() for g in line.split(",")[:-1]]
        a = A(fname, lname, age)
        print(a)

Result:

fname=Jack, lname=Hugman, age=22
fname=Joe, lname=Zareil, age=32
fname=Ashely, lname=Timberlake, age=28

If your want to use only those lines with exactly three fields, do this:

with open("in.txt") as f:
    for line in f:
        fields = [g.strip() for g in line.split(",")]
        if len(fields) == 3:
            a = A(fields[0], fields[1], fields[2])
            print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM