Re: File Reading related query

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tim Chase

    Re: File Reading related query

    >Is there any function for reading a file while ignoring *\n* occuring in
    >the file?
    >
    can you be a bit more precise? are we talking about text files or
    binary files? how do you want to treat any newlines that actually
    appear in the file?
    I believe the OP is referencing this behavior:

    for line in file('x.txt'):
    assert not (
    line.endswith(' \r') or
    line.endswith(' \n')), "Don't want this"
    else:
    yay() # we never end up reaching this

    which can be done with a simple generator/wrapper:

    def unnewline(itera tor):
    for line in iterator:
    yield line.rstrip('\r \n')
    for line in unnewline(file( 'x.txt')):
    assert not (
    line.endswith(' \r') or
    line.endswith(' \n')), "Don't want this"
    else:
    yay() # we get here this time

    Alternatively, the content can just be modified on the fly:

    for line in file('x.txt'):
    line = line.rstrip('\r \n')
    ...

    yes, the interpretation would differ if it were a binary file,
    but the above interpretation is a pretty common case (i.e. I
    encounter it daily, in my processing of client data-feeds).

    -tkc


Working...