Back to Study Material Python

Write and Create Files

Writing files in Python is as straightforward as reading them, but you need to understand the different modes to avoid accidentally overwriting data you wa...

Write and Create Files

Writing and Creating Files in Python

Writing files in Python is as straightforward as reading them, but you need to understand the different modes to avoid accidentally overwriting data you want to keep. The write mode "w" creates a new file or truncates an existing one to zero length before writing. The append mode "a" adds new content at the end of an existing file without touching what is already there.

with open("output.txt", "w", encoding="utf-8") as f: f.write("Hello, World!\n") f.write("This is a second line.\n")

The write() method writes a string and returns the number of characters written. Unlike print(), it does not add a newline automatically, so you need to include "\n" explicitly at the end of each line if you want them on separate lines. The writelines() method accepts a list of strings and writes them all in sequence, again without adding newlines between them.

lines = ["First line\n", "Second line\n", "Third line\n"] with open("output.txt", "w", encoding="utf-8") as f: f.writelines(lines)

To create a file only if it does not already exist, use the exclusive creation mode "x". If the file already exists, Python raises a FileExistsError. This is useful when you want to avoid overwriting data.

try: with open("new_file.txt", "x", encoding="utf-8") as f: f.write("Created fresh.") except FileExistsError: print("File already exists, skipping.")

For binary files like images or compiled data, use "wb" or "ab" mode. The content you write must be of type bytes, not str.

When writing large amounts of data, Python buffers writes in memory and flushes them to disk periodically. You can force an immediate flush with f.flush(), which is useful when you need another process to read the file before it is closed. The data is also flushed when the with block exits.

Python does not create intermediate directories automatically. If you try to write to "data/output/results.txt" and the data or output directories do not exist, you get a FileNotFoundError. Use os.makedirs() or pathlib.Path.mkdir() with parents=True to create the full path first.

Interview tip: Explain the difference between "w" and "a" modes clearly. A common mistake is using "w" when the intent is to append, accidentally destroying existing data. Also mention that "x" mode is the safest way to create a new file when you must not overwrite an existing one.