Working with files
Reading from and writing to files, redirecting stdin/stdout for file-based judges, and a local testing workflow.
Opening and Closing Files
The basic way to open a file in Python is the open() function:
Always closing the file is easy to forget. The preferred way is using a with block — it closes the file automatically when the block ends, even if an error occurs:
Always use with. There is no reason to use the manual open / close pattern.
File Modes
The second argument to open() is the mode:
| Mode | Meaning |
|---|---|
"r" | Read (default) |
"w" | Write — creates file or overwrites existing |
"a" | Append — adds to end of existing file |
"r+" | Read and write |
Reading from a File
Read the entire file as one string:
Read all lines as a list:
Read line by line — memory efficient for large files:
Read a single line:
Writing to a File
write() does not add a newline automatically — you must include \n yourself.
To write multiple lines at once:
Or use writelines() — it writes each string in the list without adding separators:
Redirecting stdin and stdout to Files
Some judges expect you to redirect standard I/O to files, while keeping your solution code unchanged. You can do this at the top of your solution without modifying the reading/writing logic: