i have following code:
file = open("file", "r") array = file.readlines() stats = [1, 1, 1, 1, 1] # creating array fill print array sh1 = array[1] # breaking array extracted text file editing sh2 = array[2] sh3 = array[3] sh4 = array[4] stats[0] = string.rstrip(sh1[1]) stats[1] = string.rstrip(sh2[1]) stats[2] = string.rstrip(sh3[1]) stats[3] = string.rstrip(sh4[1]) print stats i expecting strip newlines array extracted text file , place new data separate array. instead happening i'm having seemingly random amount of characters stripped either end of variables. please explain i've done wrong?
you should open file using with, don't need call readlines first. can iterate on file object in list comprehension calling rstrip on each line:
with open("file") f: # closes file automatically stats = [line.rstrip() line in f] why code removes random characters because passing random characters remove, passing second character second, third,fourth , fifth lines respectively rstrip , stripping lines 1,2,3 , 4 depending on strings end , passed different chars removed. can pass no substring remove whitespace or specify characters:
in [3]: "foobar".rstrip("bar") out[3]: 'foo' in [4]: "foobar \n".rstrip() out[4]: 'foobar' there no way removing data front of string unless stripping string. lastly if want skip first line , start @ line 2 have call next(f) on file object before iterate in comprehension.
Comments
Post a Comment