Newby Question for reading a file

steven.oldner steven.oldner at gmail.com
Thu Feb 19 21:10:22 CET 2009


On Feb 19, 1:44 pm, Curt Hash <curt.h... at gmail.com> wrote:
> On Thu, Feb 19, 2009 at 12:07 PM, steven.oldner <steven.old... at gmail.com> wrote:
>
> > On Feb 19, 12:40 pm, Mike Driscoll <kyoso... at gmail.com> wrote:
> > > On Feb 19, 12:32 pm, "steven.oldner" <steven.old... at gmail.com> wrote:
>
> > > > Simple question but I haven't found an answer.  I program in ABAP, and
> > > > in ABAP you define the data structure of the file and move the file
> > > > line into the structure, and then do something to the fields.  That's
> > > > my mental reference.
>
> > > > How do I separate or address each field in the file line with PYTHON?
> > > > What's the correct way of thinking?
>
> > > > Thanks!
>
> > > I don't really follow what you mean since I've never used ABAP, but
> > > here's how I typically read a file in Python:
>
> > > f = open("someFile.txt")
> > > for line in f:
> > >     # do something with the line
> > >     print line
> > > f.close()
>
> > > Of course, you can read just portions of the file too, using something
> > > like this:
>
> > > f.read(64)
>
> > > Which will read 64 bytes. For more info, check the following out:
>
> > >http://www.diveintopython.org/file_handling/file_objects.html
>
> > >  - Mike
>
> > Hi Mike,
>
> > ABAP is loosely based on COBOL.
>
> > Here is what I was trying to do, but ended up just coding in ABAP.
>
> > Read a 4 column text file of about 1,000 lines and compare the 2
> > middle field of each line.  If there is a difference, output the line.
>
> > The line's definition in ABAP is PERNR(8) type c, ENDDA(10) type c,
> > BEGDA(10) type c, and LGART(4) type c.
> > In ABAP the code is:
> > LOOP AT in_file.
> >  IF in_file-endda <> in_file-begda.
> >    WRITE:\ in_file. " that's same as python's print
> >  ENDIF.
> > ENDLOOP.
>
> > I can read the file, but didn't know how to look st the fields in the
> > line.  From what you wrote, I need to read each segment/field of the
> > line?
>
> > Thanks,
>
> > Steve
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> You could do something like this:
>
> f = open('file.txt', 'r')
> for line in f:
>     a,b = line.split()[1:-1]   # tokenize the string into sequence of
> length 4 and store two middle values in a and b
>     if a != b:
>         print line
> f.close()- Hide quoted text -
>
> - Show quoted text -

Peter, you are correct, just fields glued together.  I did not know
there was a struc module and that code looks real good.  This is
something I will use in the future. Thanks!

Curt, that looks good also.  I just need to test the 2 middle values.
I didn't know how to store line.split values into variables and this
is simple. Thanks!

Again, thanks Mike, Peter and Curt.  Now if you ever need to know
ABAP... ;)







More information about the Python-list mailing list