Python · files

File Writing

Create files, replace their contents or add to the end, and know exactly what ends up on disk.

Write mode


          # write to file (overwrites)
          with open("output.txt", "w") as file:
              file.write("Hello, World!")
        

Opening with "w" empties the file straight away (or creates it if it is missing).

Write multiple lines


          # write several lines
          with open("output.txt", "w") as file:
              file.write("Line 1\n")
              file.write("Line 2\n")
              file.write("Line 3\n")
        

Each line needs its own \n; write never adds one.

writelines


          # write list of lines
          lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
          with open("output.txt", "w") as file:
              file.writelines(lines)
        

Append mode


          # append to existing file
          with open("output.txt", "a") as file:
              file.write("Appended line\n")
        

With "a" the old contents stay and the cursor starts at the end.

write returns a count


          # write returns character count
          with open("output.txt", "w") as file:
              count = file.write("Hello")
          # ans: count is 5
        

Exercises

Predict what ends up in the file, then reveal.

Exercise 1


          # write mode behavior?
          with open("file.txt", "w") as f:
              f.write("New content")
          # ans: overwrites existing file
        

Exercise 2


          # write adds newline?
          with open("file.txt", "w") as f:
              f.write("Line 1")
              f.write("Line 2")
          # ans: "Line 1Line 2" (no newline)
        

Exercise 3


          # writelines adds newlines?
          lines = ["A", "B", "C"]
          with open("file.txt", "w") as f:
              f.writelines(lines)
          # ans: "ABC" (no newlines)
        

Exercise 4


          # append to non-existent?
          with open("new.txt", "a") as f:
              f.write("Text")
          # ans: creates new file
        

Exercise 5


          # write empty string?
          with open("file.txt", "w") as f:
              f.write("")
          # ans: creates empty file
        

Exercise 6


          # write number?
          with open("file.txt", "w") as f:
              f.write(42)
          # ans: TypeError (must be string)
        

Convert first: f.write(str(42)).

Exercise 7


          # write return value?
          with open("file.txt", "w") as f:
              n = f.write("Hi")
          # ans: n is 2
        

Exercise 8


          # write in read mode?
          with open("file.txt", "r") as f:
              f.write("Text")
          # ans: io.UnsupportedOperation
        

Exercise 9


        # append vs write?
        # ans: "w" overwrites
        # ans: "a" adds to end
      

Exercise 10


          # write binary?
          with open("file.bin", "wb") as f:
              f.write(b"data")
          # ans: writes bytes
        

In binary mode, write takes bytes (note the b prefix), not str.

Remember

"w"

Empties the file (or creates it), then writes from the start.

"a"

Keeps what is there and writes at the end; creates the file if needed.

No automatic newlines

write and writelines write exactly the strings you give, so add \n yourself.

Strings only

write returns the number of characters; numbers must go through str(); binary mode takes bytes.