6.4 File Writing Methods

6.4 File Writing Methods

Learning the write() and writelines() methods for writing data to files, with an emphasis on manually adding the newline character.

For writing data to a file opened in write (`"w"`) or append (`"a"`) mode, the main methods are `write()` and `writelines()`.
  • `write(string)`: Writes a single string to the file. It is important to remember that `write()` does not automatically add a newline character (`\n`). You must add it manually if you want your data to be on separate lines.
  • `writelines(list_of_strings)`: Accepts a list of strings and writes them to the file, one after the other. Similarly, it does not automatically add newlines. Each item in the list must contain the `\n` character if you want a line break.
# 1. Using write()
with open("write_methods_example.txt", "w", encoding="utf-8") as f:
    f.write("First line.\n")
    f.write("Second line.\n")

# 2. Using writelines()
lines_to_write = ["Third line.\n", "Fourth line.\n"]
with open("write_methods_example.txt", "a", encoding="utf-8") as f:
    f.writelines(lines_to_write)

# Confirmation
with open("write_methods_example.txt", "r", encoding="utf-8") as f:
    print("Content of 'write_methods_example.txt':")
    print(f.read())

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.