Python:读文件和写文件


Python:读文件和写文件

1. 写文件

[python]
  1. #! /usr/bin/python3   
  2.   
  3. 'makeTextFile.py -- create text file'  
  4.   
  5. import os  
  6.   
  7. def write_file():  
  8.     "used to write a text file."  
  9.       
  10.     ls = os.linesep  
  11.     #get filename   
  12.     fname = input("Please input filename:")  
  13.   
  14.     while True:  
  15.       
  16.         if os.path.exists(fname):  
  17.             print("Error: '%s' already exists" % fname)  
  18.             fname = input("Please input filename:")  
  19.         else:  
  20.             break  
  21.           
  22.     #get file conent linesOnScreen   
  23.     all = []  
  24.     print("\nEnter lines ('.' to quit).\n")  
  25.   
  26.     while True:  
  27.         entry = input('>')  
  28.         if entry == '.':  
  29.             break  
  30.         else:  
  31.             all.append(entry)  
  32.               
  33.     try:  
  34.         fobj = open(fname,  'w')  
  35.     except IOError as err:  
  36.         print('file open error: {0}'.format(err))    
  37.           
  38.     fobj.writelines(['%s%s' % (x,  ls) for x in all])  
  39.     fobj.close()  
  40.       
  41.     print('WRITE FILE DONE!')  
  42.       
  43.     return fname  

2. 读文件

[python]
  1. #! /usr/bin/python3   
  2.   
  3. 'readTextFile.py -- read and display text file.'  
  4.   
  5. def read_file(filename):  
  6.     'used to read a text file.'  
  7.       
  8.     try:  
  9.         fobj = open(filename,  'r')  
  10.     except IOError as err:  
  11.         print('file open error: {0}'.format(err))    
  12.     else:  
  13.         for eachLine in fobj:  
  14.             print(eachLine)  
  15.         fobj.close()  
  16.           
  17.   
  18.       

3. 主程序

[python]
  1. #! /usr/bin/python3   
  2.   
  3. 'write_and_read_file.py -- write and read text file.'  
  4.   
  5. import makeTextFile  
  6. import readTextFile  
  7.   
  8. if __name__ == '__main__':  
  9.       
  10.     #wrie file   
  11.     filename = makeTextFile.write_file()  
  12.       
  13.     #read file   
  14.     readTextFile.read_file(filename)  

4.运行结果

[html]
  1. Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on winxp-duanyx, Standard  
  2. >>> Please input filename:d:\testpython.log  
  3.   
  4. Enter lines ('.' to quit).  
  5.   
  6. >this is a test file.  
  7. >ok ,let us input . to end the content input.  
  8. >.  
  9. WRITE FILE DONE!  
  10. this is a test file.  
  11.   
  12.   
  13.   
  14. ok ,let us input . to end the content input.  
  15.   
  16.   
  17.   
  18.   
  19. >>>   

相关内容