Writing files

Part of the free LogicWiz Python course, Module 8: Files. The examples and practice run in the app.

Aarav saved Monday's sales to sales.txt. On Tuesday he saved again, and Monday's sales were gone. One letter wiped them: "w".

You'll learn to

  • Pick the right mode: `w`, `a`, `r+`, `w+`, `a+`
  • Write with `write()` and `writelines()`, adding your own newlines
  • Move around a file with `seek()` and `tell()`, and predict board-style outputs

Learn

File modes

ModeWhat it does
"r"Read only. File must exist. Starts at the beginning.
"w"Write. Creates the file, and wipes it if it exists.
"a"Append. Creates the file if needed. Every write goes to the end; nothing is wiped.
"r+"Read and write. File must exist. Starts at the beginning and overwrites in place.
"w+"Write and read. Creates, and wipes.
"a+"Append and read. Creates if needed; writes always go to the end; the pointer starts at the end.

"w" wipes

with open("sales.txt", "w") as f:
    f.write("Monday: Rs 2450\n")

with open("sales.txt", "w") as f:
    f.write("Tuesday: Rs 3100\n")

with open("sales.txt") as f:
    print(f.read())

Only Tuesday survives. Opening with "w" empties the file at once, before you write anything.

"a" adds to the end

with open("sales.txt", "w") as f:
    f.write("Monday: Rs 2450\n")

with open("sales.txt", "a") as f:
    f.write("Tuesday: Rs 3100\n")

with open("sales.txt") as f:
    print(f.read())

Use "a" for logs and daily records: each run adds, nothing is lost.

write vs writelines

  • f.write(text) writes one string and returns the number of characters written. It does not add a newline: you add "\n" yourself. It only takes strings, so f.write(15) is a TypeError; write str(15).
  • f.writelines(list_of_strings) writes every string in the list, one after another. Despite the name it adds no newlines either, and it returns None.

Both in action

items = ["samosa\n", "chai\n", "dosa\n"]
with open("menu.txt", "w") as f:
    n = f.write("MENU\n")
    f.writelines(items)
    f.write(str(len(items)) + " items\n")
print("first write returned", n)

with open("menu.txt") as f:
    print(f.read())

"MENU\n" is 5 characters, so write returned 5. Try removing the \n from the items and see them run together.

seek and tell

An open file has a pointer: the position where the next read or write happens.

  • f.tell() returns the current position (characters from the start, for plain English text).
  • f.seek(n) moves the pointer to position n. f.seek(0) goes back to the start.

After a write, the pointer sits at the end of what you wrote. So in "w+" mode, reading straight after writing gives "": seek back to 0 first.

seek and tell, step by step

with open("demo.txt", "w+") as f:
    f.write("CANTEEN")
    print(f.tell())
    f.seek(0)
    print(f.read(3))
    print(f.tell())
    f.seek(4)
    print(f.read())

After writing 7 characters the pointer is at 7. Back to 0, read 3 ("CAN"), now at 3. Jump to 4 and read the rest ("EEN"). Positions count from 0, like list indexes.

"r+" does not insert: writing at the start overwrites the characters already there. And "w" or "w+" wipes the file the moment it opens, even if you never write a byte. When in doubt about keeping old data, use "a".

Board favourites: "differentiate w and a", "r+ vs w+", and output questions with seek()/tell(). In text mode, use seek(0) or a value you got from tell(); the full form seek(offset, whence) (0 = start, 1 = current, 2 = end) is mainly for binary files.

In one line

"w" wipes, "a" appends, "r+" overwrites in place; write adds no newline and returns the count; tell() is where you are, seek(n) jumps there.