歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python:讀文件和寫文件

Python:讀文件和寫文件

日期:2017/3/1 10:32:34   编辑:Linux編程

Python:讀文件和寫文件

1. 寫文件

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

2. 讀文件

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

3. 主程序

[python]
  1. #! /usr/bin/python3
  2. 'write_and_read_file.py -- write and read text file.'
  3. import makeTextFile
  4. import readTextFile
  5. if __name__ == '__main__':
  6. #wrie file
  7. filename = makeTextFile.write_file()
  8. #read file
  9. 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. Enter lines ('.' to quit).
  4. >this is a test file.
  5. >ok ,let us input . to end the content input.
  6. >.
  7. WRITE FILE DONE!
  8. this is a test file.
  9. ok ,let us input . to end the content input.
  10. >>>
Copyright © Linux教程網 All Rights Reserved