Working with files
Learn how to work with files in Python
Working with Files
Most modern online judges read input from standard input (stdin) and expect output to standard output (stdout) — you never touch the file system at all. However, some older judges and certain problem formats require reading from a file like input.txt and writing to output.txt. This lesson covers how to do that, plus general file handling skills useful outside of contests.
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 yourself.