Python: Read/Write to File

By Xah Lee. Date: . Last updated: .

To open a file and write to file do:

f = open('xfile.txt','w')

This creates a file “object”.

The second argument of “open” can be 'w' for write (overwrite exsiting file), 'a' for append, 'r' for read only.

To actually print to or read from file, use the file object's methods.

Read entire file:

text =

Read one line at a time:

line = f.readline()

Read entire file as a list of lines:

mylist = f.readlines()

To write to file, do:

f.write('yay, first line!\n')

When you are done, close the file:


Closing files saves memory while the program is still running. You should always do that.

Here is a complete example of reading in a file and writing it to another file.

# python 3

f1 = open("/Users/joe/in.txt","r")
f2 = open("/Users/joe/out.txt","w")

for xx in f1:


Using 「with」 to Open File

Alternatively, you can use with:

# python 3

# example of opening file, using 「with」

with open("/home/joe/file.html", "r") as f:
    for x in f:

When using with, you do not need to close the file. Python will close any file opened within it, when the with block is done.

thank to Kurt Schwehr for showing me “with”.

Python Text Processing

  1. Read/Write File
  2. Walk Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Convert File Encoding in a Dir
  7. Find Replace in dir
  8. Find Replace by Regex
  9. Count Word Frequency

If you have a question, put $5 at patreon and message me.


  1. Python 3 Basics
  2. Python 2 Basics
  3. Python 2 and 3 Difference
  4. Print Version
  5. Builtin Help
  6. Quote String
  7. String Methods
  8. Format String
  9. Operators
  10. Complex Numbers
  11. True, False
  12. if then else
  13. Loop
  14. List Basics
  15. Loop Thru List
  16. Map f to List
  17. Copy Nested List
  18. List Comprehension
  19. List Methods
  20. Sort
  21. Dictionary
  22. Loop Thru Dict
  23. Dict Methods
  24. Tuple
  25. Sets
  26. Function
  27. Closure
  28. 2 Closure
  29. Decorator
  30. Class
  31. Object, ID, Type
  32. List Modules
  33. Write a Module
  34. Unicode 🐍


  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. File Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency


  1. Send Email
  2. GET Web Page
  3. Web Crawler


  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Append String in Loop
  7. Timing f timeit
  8. Keyword Arg Default Value Unstable
  9. Check Page Load Size
  10. Thumbnail Generation