# write to file (overwrites)with open("output.txt", "w") as file: file.write("Hello, World!")
# write several lineswith open("output.txt", "w") as file: file.write("Line 1\n") file.write("Line 2\n") file.write("Line 3\n")
# write list of lineslines = ["Line 1\n", "Line 2\n", "Line 3\n"]with open("output.txt", "w") as file: file.writelines(lines)
# append to existing filewith open("output.txt", "a") as file: file.write("Appended line\n")
# write returns character countwith open("output.txt", "w") as file: count = file.write("Hello")#ans: count is 5
# 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)
# 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
Google tag (gtag.js)