Checking if a text file is blank

David wizzardx at gmail.com
Sun Apr 20 02:26:27 EDT 2008


>
>  Is there any way in python to check if a text file is blank?
>
>  What I've tried to do so far is:
>
>                 f = file("friends.txt", "w")
>                 if f.read() is True:
>                         """do stuff"""
>                 else:
>                         """do other stuff"""
>                 f.close()
>
>  What I *mean* to do in the second line is to check if the text file is
>  not-blank. But apparently that's not the way to do it.
>
>  Could someone set me straight please?

You're opening your file in write mode, so it gets truncated. Add "+"
to your open mode (r+ or w+) if you want to read and write.

Here is the file docstring:

    file(name[, mode[, buffering]]) -> file object

    Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
    writing or appending.  The file will be created if it doesn't exist
    when opened for writing or appending; it will be truncated when
    opened for writing.  Add a 'b' to the mode for binary files.
    Add a '+' to the mode to allow simultaneous reading and writing.
    If the buffering argument is given, 0 means unbuffered, 1 means line
    buffered, and larger numbers specify the buffer size.
    Add a 'U' to mode to open the file for input with universal newline
    support.  Any line ending in the input file will be seen as a '\n'
    in Python.  Also, a file so opened gains the attribute 'newlines';
    the value for this attribute is one of None (no newline read yet),
    '\r', '\n', '\r\n' or a tuple containing all the newline types seen.

    'U' cannot be combined with 'w' or '+' mode.

    Note:  open() is an alias for file().

Also, comparison of a value with True is redundant in an if statement.
Rather use 'if f.read():'

David.



More information about the Python-list mailing list