read files

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Jan 21 22:50:50 EST 2008


On Tue, 22 Jan 2008 11:00:53 +0800, J. Peng wrote:

> first I know this is the correct method to read and print a file:
> 
> fd = open("/etc/sysctl.conf")
> done=0
> while not done:
>     line = fd.readline()
>     if line == '':
>         done = 1
>     else:
>         print line,
> 
> fd.close()


The evolution of a Python program.

# Solution 2:

fd = open("/etc/sysctl.conf")
done = False
while not done:
    line = fd.readline()
    if line:
        print line,
    else:
        done = True
fd.close()



# Solution 3:

fd = open("/etc/sysctl.conf")
while True:
    line = fd.readline()
    if line:
        print line,
    else:
        break
fd.close()


# Solution 4:

fd = open("/etc/sysctl.conf")
lines = fd.readlines()
for line in lines:
    print line,
fd.close()


# Solution 5:

fd = open("/etc/sysctl.conf", "r")
for line in fd.readlines():
    print line,
fd.close()


# Solution 6:

for line in open("/etc/sysctl.conf").readlines():
    print line,
# garbage collector will close the file (eventually)


# Solution 7:

fd = open("/etc/sysctl.conf", "r")
line = fd.readline()
while line:
    print line,
    line = fd.readline()
fd.close()


# Solution 8:

fd = open("/etc/sysctl.conf", "r")
for line in fd:
    print line,
fd.close()


# Solution 9:

for line in open("/etc/sysctl.conf"):
    print line,


# Solution 10:
# (the paranoid developer)

try:
    fd = open("/etc/sysctl.conf", "r")
except IOError, e:
    log_error(e)  # defined elsewhere
    print "Can't open file, please try another."
else:
    try:
        for line in fd:
            print line,
    except Exception, e:
        log_error(e)
        print "Reading file was interrupted by an unexpected error."
    try:
        fd.close()
    except IOError, e:
        # Can't close a file??? That's BAD news.
        log_error(e)
        raise e




-- 
Steven



More information about the Python-list mailing list