开发者

.startswith not working

In My program I have a file and then I read through all the lines in a for loop checking each line for what it begins with. Then adding each line as a variable. There are a little over 40 lines in this and they are all pretty much the same but one of the elif statements doesnt return true the .startswith isnt working. anyways here is the file contents basically a bunch of saved information fN would be the variable I saved and john would be what I want it to be. So this method does just that or it is suppose to

fN:john
fP:1
fE:father email
mN:mother name
mP:1
mE:mother email @ bomg.com
a:1233 adress lane
c:city
s:state
zC:1234534
hP:(1928)phone-1123
cP:1113333
eN:emergancy
eNu:number
c1N:cluubiie 1
c1G:1st
c1B:1-23-34
c2N:clubbie 2
c2G:grade 2
c2B:birth 2
c3N:clubb 3 
c3G:grade 3
c3B:birth 3

Method

def fillWindow(self,student):
    global fileDirectory
    location = os.path.join(fileDirectory, student + '.txt')
    file = open(location, 'r')

    for line in file.xreadlines():
        if line.startswith('fN'):
            fN = line.split(':')[1]
        elif line.startswith('fP'):
            fP = line.split(':')[1]
        elif line.startswith('fE'):
            fE = line.split(':')[1]
        elif line.startswith('mN'):
            mN = line.split(':')[1]
        elif line.startswith('mP'):
            mP = line.split(':')[1]
        elif line.startswith('mE'):
            mE = line.split(':')[1]
        elif line.startswith('a'):
            a = line.split(':')[1]
        elif line.startswith('c')开发者_运维知识库:
            c = line.split(':')[1] 
        elif line.startswith('s'):
            s = line.split(':')[1]
        elif line.startswith('zC'):
            zC = line.split(':')[1]
        elif line.startswith('hP'):
            hP = line.split(':')[1]

right here True is never returned even though in the file there is a line that starts with cP

        elif line.startswith('cP'):
            cP = line.split(':')[1]
            print('True') 
        elif line.startswith('eN'):
            eN = line.split(':')[1]
        elif line.startswith('eNu'):
            eNu = line.split(':')[1]
        elif line.startswith('c1N'):
            c1N = line.split(':')[1] 
        elif line.startswith('c1G'):
            c1G = line.split(':')[1]
        elif line.startswith('c1B'):
            c1B = line.split(':')[1] 
        elif line.startswith('c2N'):
            c2N = line.split(':')[1] 
        elif line.startswith('c2G'):
            c2G = line.split(':')[1]
        elif line.startswith('c2B'):
            c2B = line.split(':')[1]
        elif line.startswith('c3N'):
            c3N = line.split(':')[1] 
        elif line.startswith('c3G'):
            c3G = line.split(':')[1]
        elif line.startswith('c3B'):
            c3B = line.split(':')[1]
        elif line.startswith('c4N'):
            c4N = line.split(':')[1] 
        elif line.startswith('c4G'):
            c4G = line.split(':')[1]
        elif line.startswith('c4B'):
            c4B = line.split(':')[1]


You should think about how these two lines interact:

elif line.startswith('c'):
...
elif line.startswith('cP'):

Also, you should look into using a dictionary to hold all your values, you could drastically shorten your program.


That's a pretty horrible chunk of code. Do you really need all those elements to be individual variables? Why not a dictionary along these lines:

{'fN':'john',
 'fP':'1',
   ...
}

which you could generate in a couple of lines only:

dct = {}
f = file(location, 'r')
for line in f:
    k, v = line.split(':')
    dct[k] = v


Since you are using elif for all alternatives but the first one, at most one of the alternatives ever gets evaluated. For a line starting with cP, the condition

elif line.startswith('c'):

will also hold, so none of the further alternatives will be considered.

That said, you might be better off storing your result in a dictionary, maybe like this:

d = dict(line.split(":", 1) for line in open(location))


It does not work because a line starts with cP also starts with c, and you placed the c condition before cP.


You should better refactor your code to avoid the long if/elif chain. It is very unmaintainable. I would use a dictionary and

 results = {}
 for line in file:
    (key, value) = line.split(':', 1)
    results[key] = value

 # use results['fN'] for your fN variable

or even shorter:

 results = dict(line.split(':', 1) for line in file)

(If you must use fN as an independent local variable, you could use

 locals().update(line.split(':', 1) for line in file)

but I don't recommend it.)


Since the names fN , fP , fE , mN, mP, .... are manifestly known and steady, and since the self in your definition of the function betrays you want to create attributes of an instance with values read in the file, and since the file has a CSV format, my proposition is to do:

import csv

class A:
def __init__(self):
    self.fN  = self.fP  = self.fE  = None 
    self.mN  = self.mP  = self.mE  = None
    self.a   = self.c   = self.s   = None
    self.zC  = self.hP  = self.cP  = None
    self.eN  = self.c1N = self.c1G = None
    self.c1B = self.c2N = self.c2G = None
    self.c2B = self.c3N = self.c3G = None
    self.c3B = None

inst1 = A()

with open('roro.txt','rb') as f:
    rid = csv.reader(f,delimiter=':')
    for row in rid:
        inst1.__dict__[row[0]] = row[1]


print inst1.fP
print inst1.s
print inst1.c3B

Note that naming an object with the name of a built-in function ( that is to say file) is a bad practice, and that xreadlines() is deprecated.

.

Moreover, what is your intention by defining global fileDirectory ?

The statement global x specifies that if the creation of an object is done thanks to an assignement done to name x in the next lines, the object of name x must be considered as being in the module of global level. In your code there is no assignement to fileDirectory and it's better because declaring fileDirectory as global could provoke unsuspected errors.

Note that the global level is the higher level , not the outside level of a function. Examine the following code:

class A:

    def __init__(self):
        self.m = 0.00315879

    N = 101

    def f(self,x,y):
        print 'in f : x==',x,"  y+10==",y
        def g(a,b):
            print 'in g : a==',a,'  b==',b
            global m
            global N
            m = a*b
            N = 5000010000
            print 'in g : m = a*b ==',m
            print 'in g : N==',N


        g(x+300,y+700)
        print 'in f, outside g: m==',m
        print 'in f, outside g: N==',N



u = A()


u.f(0,40)
print
print 'm at the global level==',m
print 'N at the global level==',N
print 'the instance attribute u.m==',u.m
print 'the class attribute u.N==',u.N

result

in f : x== 0   y+10== 40
in g : a== 300   b== 740
in g : m = a*b == 222000
in g : N== 5000010000
in f, outside g: m== 222000
in f, outside g: N== 5000010000

m at the global level== 222000
N at the global level== 5000010000
the instance attribute u.m== 0.00315879
the class attribute u.N== 101
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜