Python:读文件和写文件

最后更新于:2022-04-01 19:39:28

1. 写文件 ~~~ #! /usr/bin/python3 'makeTextFile.py -- create text file' import os def write_file(): "used to write a text file." ls = os.linesep #get filename fname = input("Please input filename:") while True: if os.path.exists(fname): print("Error: '%s' already exists" % fname) fname = input("Please input filename:") else: break #get file conent linesOnScreen all = [] print("\nEnter lines ('.' to quit).\n") while True: entry = input('>') if entry == '.': break else: all.append(entry) try: fobj = open(fname, 'w') except IOError as err: print('file open error: {0}'.format(err)) fobj.writelines(['%s%s' % (x, ls) for x in all]) fobj.close() print('WRITE FILE DONE!') return fname ~~~ 2. 读文件 ~~~ #! /usr/bin/python3 'readTextFile.py -- read and display text file.' def read_file(filename): 'used to read a text file.' try: fobj = open(filename, 'r') except IOError as err: print('file open error: {0}'.format(err)) else: for eachLine in fobj: print(eachLine) fobj.close() ~~~ 3. 主程序 ~~~ #! /usr/bin/python3 'write_and_read_file.py -- write and read text file.' import makeTextFile import readTextFile if __name__ == '__main__': #wrie file filename = makeTextFile.write_file() #read file readTextFile.read_file(filename) ~~~ 4.运行结果 ~~~ Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on winxp-duanyx, Standard >>> Please input filename:d:\testpython.log Enter lines ('.' to quit). >this is a test file. >ok ,let us input . to end the content input. >. WRITE FILE DONE! this is a test file. ok ,let us input . to end the content input. >>> ~~~
';