[Tutor] text file help
Alan Gauld
alan.gauld at btinternet.com
Thu Feb 19 13:21:19 CET 2015
Forwarding to tutor, please use Reply All when responding to tutor emails.
On 19/02/15 11:17, Tihomir Zjajic wrote:
> formular doznake.txt
>> red_broj = 1
>> vrs_drv = 21
>> prs_prec = 20
>> teh_kl = 2
>> red_broj = 2
>> vrs_drv = 21
>> prs_prec = 40
>> teh_kl = 3
>
> I assume red_broj indicates the start of a new record?
> So you can read three lines from the file after you
> find a red_broj entry?
>
> Something like this? (untested)
>
> kl_numbers = []
> with open('doznake.txt') as doznake
> for line in doznake:
> if line.startswith('red_broj')
> num = makeNumber(next(doznake),next(doznake),next(doznake))
> kl_numbers.append(num)
>
> def makeNumber(l1,l2,l3):
> nums = []
> for line in (s1,s2,s3):
> nums.append(line.rstrip().split()[-1])
> return ''.join(nums)
> def makeNumber(l1, l2, l3):
> nums = []
> for lines in (s1, s2, s3):
> nums.append(line.rstrip().split() [-1])
> return ".join(nums) "
>
> kl_number = []
> open("formular_doznake.txt")
You need to either assign the open result to a variable or use
the 'with' style (as in my example above).
> for line in "formular_doznake.txt":
> line startswith("red_broj")
startswith is a method of string so you need a dot between line and
startswith
> num = makeNumber(next("formular_doznake"),
next("formular_doznake"), next("formular_doznake"))
next takes an iterator as an argument not a file name. This needs to
be the alias from the with statement or the variable you assign if using
open.
example:
>>> myfile = open("formular_doznake.txt")
>>> print(next(myfile))
> kl_number.append(num)
>
> lpthw> python answer2.py formular_doznake.txt
> File "answer2.py" line 13
> kl_number.append(num)
> SyntaxError: invalid sintax
You should copy and paste the code and errors not re-type them.
its easier and more reliable.
BTW If using the open styule above you should close the file
at the end:
myfile.close()
One of the advantages of the with... style is that it auto-closes
the file for you.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list