Python 读写文件的两个简单实例

写:

import os

# get filename
while True:
    filename = raw_input("Please input file name: ")
    if os.path.exists(filename):
        print 'Error: "%s" exists' % filename
    else:
        break

# get file content
all = []
print "Enter lines '.' to quit.\n"

# loop until user terminate input
while True:
    line = raw_input('> ')
    if line == '.':
        break
    else:
        all.append(line)

# write line to file
fobj = open(filename, 'w')
fobj.write('\n'.join(all))
fobj.close()

print 'Done!'

读:

# get filename
fname = raw_input('Enter filename: ')
print

# attemp to open file for reading
try:
    fobj = open(fname, 'r')
except IOError, e:
    print "*** file open error:", e
else:
    # display contents to the screen
    for eachLine in fobj:
        print eachLine,
    fobj.close()


你可能感兴趣的:(Python)