Writing in File
M3-R5.1 · Chapter 7: File Processing · 2 min read
Writing into File
4.1 write() Function
write(string) writes the given string to the file. Returns the number of characters written. Does NOT automatically add a newline character.
# Writing to a file (creates or overwrites)
f = open('output.txt', 'w')
chars = f.write('Hello, World!') # Returns 13 (number of chars written)
print(chars) # Output: 13
f.write('\nThis is line 2.') # Must manually add \n
f.write('\nThis is line 3.')
f.close()
# Appending to existing file
f = open('output.txt', 'a')
f.write('\nThis line is appended.')
f.close()
📌 Important
write() mode ('w') will DELETE all existing content of the file before writing. To add data without erasing, always use append mode ('a').
4.2 writelines() Function
writelines(list) writes a list (or any iterable) of strings to the file. Does NOT add newlines automatically between items.
lines = ['First line\n', 'Second line\n', 'Third line\n']
# Write list of strings to file
f = open('output.txt', 'w')
f.writelines(lines) # Writes all strings in the list
f.close()
# writelines() does NOT add \n automatically
# If your list items don't have \n, they'll all be on one line!
names = ['Alice', 'Bob', 'Charlie']
f = open('names.txt', 'w')
f.writelines(name + '\n' for name in names) # Generator with \n
f.close()
▸ Difference: write() vs writelines()
|
Function |
Argument |
Returns |
Newline Handling |
|
write() |
A single string |
Number of characters written |
Does NOT add \n automatically |
|
writelines() |
List/iterable of strings |
None |
Does NOT add \n automatically |