Create files, replace their contents or add to the end, and know exactly what ends up on disk.
# 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 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.
# 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 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 character count
with open("output.txt", "w") as file:
count = file.write("Hello")
# ans: count is 5
Predict what ends up in the file, then reveal.
# write mode behavior?
with open("file.txt", "w") as f:
f.write("New content")
# ans: overwrites existing file
# write adds newline?
with open("file.txt", "w") as f:
f.write("Line 1")
f.write("Line 2")
# ans: "Line 1Line 2" (no newline)
# writelines adds newlines?
lines = ["A", "B", "C"]
with open("file.txt", "w") as f:
f.writelines(lines)
# ans: "ABC" (no newlines)
# append to non-existent?
with open("new.txt", "a") as f:
f.write("Text")
# ans: creates new file
# write empty string?
with open("file.txt", "w") as f:
f.write("")
# ans: creates empty file
# write number?
with open("file.txt", "w") as f:
f.write(42)
# ans: TypeError (must be string)
Convert first: f.write(str(42)).
# write return value?
with open("file.txt", "w") as f:
n = f.write("Hi")
# ans: n is 2
# write in read mode?
with open("file.txt", "r") as f:
f.write("Text")
# ans: io.UnsupportedOperation
# append vs write?
# ans: "w" overwrites
# ans: "a" adds to end
# 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.
"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.
write and writelines write exactly the strings you give, so add \n yourself.
write returns the number of characters; numbers must go through str(); binary mode takes bytes.