Skip to main content

How to create a text file in Python

Just need a .txt file? Create one online in seconds →

Use open() in write mode with encoding="utf-8", then call write(). This example works in Python 3.10 and later and saves notes.txt in the current working directory.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")

Method 1: Write a file with open()

1. Choose the destination

Pick a writable directory and a filename. A relative name such as notes.txt is resolved from the working directory of the running process. That may differ from the folder where the Python script lives, particularly when you run it from an IDE, notebook, or scheduled task.

2. Open the file for writing

Use with open(...) so the file is closed when Python leaves the block, including when an error occurs. Mode "w" creates the file if it is missing and empties it if it already exists. The original contents are truncated as soon as the file opens.

3. Write the text

Call write() inside the indented block. It takes a string and returns the number of characters written. Include \n where you want a line break. After the block exits, open the file in a text editor to check the result.

Choose between w, a, and x

ModeIf the file existsIf it does not existUse it for
wTruncates the fileCreates itReplace an output report
aWrites at the endCreates itAppend a log entry
xRaises FileExistsErrorCreates itSave a new file without overwriting
with open("activity.txt", "a", encoding="utf-8") as f:
    f.write("Finished export\n")

Running this twice appends two entries. If an existing file ends without a line break, the first appended string starts on the same line as the previous content. When appending to files produced by another program, match the original encoding and line-ending convention.

Write multiple lines

Use repeated write() calls, pass an iterable of strings to writelines(), or direct print() to the file. writelines() joins the strings as given, so provide any line endings yourself. print() adds a newline by default and can format values such as numbers.

with open("tasks.txt", "w", encoding="utf-8") as f:
    f.write("Today\n")
    f.writelines(["Send the draft\n", "Review the notes\n"])
    print("Task count:", 2, file=f)

Method 2: Create a file with pathlib

For a single string, Path.write_text() opens, writes, and closes the file in one call. It replaces the contents of any file at that path.

from pathlib import Path

Path("notes.txt").write_text("Hello", encoding="utf-8")

To place a file in a subdirectory, create the parent directory before writing. parents=True also creates missing ancestors. exist_ok=True allows the directory to be there already.

from pathlib import Path

output = Path("exports") / "daily" / "notes.txt"
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text("Hello\n", encoding="utf-8")

Encoding, BOM, and line endings

Set encoding="utf-8" to make the file portable when it contains characters such as é, 中文, or emoji. Defaults can vary by system and Python version. If a receiving application specifically requests UTF-8 with a byte order mark, set encoding="utf-8-sig", which adds the UTF-8 signature when writing a new file.

When writing with newline=None, the default, Python translates \n to the system's usual line separator. Set newline="\n" for consistent LF, or newline="\r\n" to produce CRLF on every platform. When you request CRLF, pass strings with \n to Python and let it do the translation. Strings containing \r\n already would get an extra CR.

with open("legacy-import.txt", "w", encoding="utf-8-sig", newline="\r\n") as f:
    f.write("Name\nRenée\n")

Encoding and line endings are separate choices. See how CRLF and LF work if a receiving program asks for one of them.

Common errors

  • FileNotFoundError when writing usually means a parent folder is missing. Check the path and create the directory before opening the file.
  • PermissionError means the requested access was denied. Try a folder you own and check whether another program has locked the file.
  • FileExistsError with mode x means Python prevented an overwrite. Use a new name, or switch to w only if you intend to replace the previous contents.
  • UnicodeEncodeError means the selected encoding cannot represent a character. For text that can contain multiple languages, use UTF-8 and confirm the reader accepts it. Changing the extension leaves the encoding intact.

Check a file before using it elsewhere

If a script will run on another computer, make its output directory explicit. For example, accept a destination path from the caller, create its parent folders where appropriate, and report the resulting path when the write succeeds. This lets the caller tell which copy to open if an older file has the same name. For a one-off script, running it from the folder where you want the output can be enough.

To check an export, reopen the file in the program that will consume it. Include a sample with the same kinds of characters and line breaks as your real data. An editor that reads either LF or CRLF can display a file correctly even when an importer requires one exact sequence. If the importer cares about the first bytes, use a byte viewer to check for a BOM as well.

Create one without code

  1. Open the editor on this page and type or paste the content.
  2. Choose a filename and the encoding and line endings required by the recipient.
  3. Download the file. Use the Windows or Mac guide to find and open it on your computer.

FAQ

How do I create an empty file?

Open it with mode x and close it without writing. Python creates a zero-byte file with UTF-8 in this case and raises an error if that name already exists.

with open("empty.txt", "x", encoding="utf-8"):
    pass

Does write() automatically add a newline?

No. Include \n in the string where you want the line to end, or use print(..., file=f) to add a newline by default. A file can contain a final line even when it ends without a newline.

Where did Python save my file?

For a relative path, check the process's working directory. Path.cwd() returns the folder Python uses as its starting point when resolving relative paths.

Sources

Create a text file online

Characters
0
Words
0
Lines
0
Bytes
0

Your text stays in your browser. Nothing is uploaded.