io_using_file.py 562 B

1234567891011121314151617181920212223242526272829
  1. poem = '''\
  2. Programming is fun
  3. When the work is done
  4. if you wanna make your work also fun:
  5. use Python!
  6. '''
  7. # Open for 'w'riting
  8. f = open('poem.txt', 'w')
  9. # Write text to file
  10. f.write(poem)
  11. # Close the file
  12. f.close()
  13. # If no mode is specified,
  14. # 'r'ead mode is assumed by default
  15. f = open('poem.txt')
  16. while True:
  17. line = f.readline()
  18. # Zero length indicates EOF
  19. if len(line) == 0:
  20. break
  21. # The `line` already has a newline
  22. # at the end of each line
  23. # since it is reading from a file.
  24. print line,
  25. # close the file
  26. f.close()