Reading and writing text files in Python


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # The built-in function `open` opens a file and returns a file object.
  2.  
  3. # Read mode opens a file for reading only.
  4. try:
  5. f = open("file.txt", "r")
  6. try:
  7. # Read the entire contents of a file at once.
  8. string = f.read()
  9. # OR read one line at a time.
  10. line = f.readline()
  11. # OR read all the lines into a list.
  12. lines = f.readlines()
  13. finally:
  14. f.close()
  15. except IOError:
  16. pass
  17.  
  18.  
  19. # Write mode creates a new file or overwrites the existing content of the file.
  20. # Write mode will _always_ destroy the existing contents of a file.
  21. try:
  22. # This will create a new file or **overwrite an existing file**.
  23. f = open("file.txt", "w")
  24. try:
  25. f.write('blah') # Write a string to a file
  26. f.writelines(lines) # Write a sequence of strings to a file
  27. finally:
  28. f.close()
  29. except IOError:
  30. pass
  31.  
  32. # Append mode adds to the existing content, e.g. for keeping a log file. Append
  33. # mode will _never_ harm the existing contents of a file.
  34. try:
  35. # This tries to open an existing file but creates a new file if necessary.
  36. logfile = open("log.txt", "a")
  37. try:
  38. logfile.write('log log log')
  39. finally:
  40. logfile.close()
  41. except IOError:
  42. pass
  43.  
  44. # There is also r+ (read and write) mode.

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.