Why files matter
Think of a file as a sticky note on your monitor. Your program runs in RAM, which is like short-term memory: fast but temporary. A file lives on the disk, which is long-term storage. You use files when you need data to survive after the script finishes—like saving game scores or keeping a running log of sensor readings.
The with statement
with open('greeting.txt', 'w') as f:
f.write('Hello from Pythos\n')
# The file is closed automatically here, even if an error occurs above.open() returns a file object. You pass the filename and a mode. Mode 'w' means write: it creates the file or erases any existing content before writing. Using with guarantees that Python closes the file for you when the block ends, preventing data corruption.Writing vs Appending
# Mode 'w': erases existing content first
with open('log.txt', 'w') as f:
f.write('line one\n')
# Mode 'a': appends after whatever exists, creating file if needed
with open('log.txt', 'a') as f:
f.write('line two\n')f.write(s) writes the string exactly as you give it. It does not add a newline character automatically. If you want each entry on its own line, include '\n' yourself at the end of your string.Reading files
# The two files from the blocks above
with open('greeting.txt', 'w') as f:
f.write('Hello from Pythos\n')
with open('log.txt', 'w') as f:
f.write('line one\nline two\n')
# Read entire file as one single string
with open('greeting.txt') as f:
text = f.read()
print(text)
# Read all lines into a list (each line keeps its trailing newline)
with open('log.txt') as f:
lines = f.readlines()
for line in lines:
print(line.strip())By default,
open() uses mode 'r' for reading. You can grab the whole file at once with .read(), or get a list of strings with .readlines(). Each string in that list includes its trailing newline character, so use .strip() to clean it up before printing.Looping over files
with open('words.txt', 'w') as f:
fruits = ['apple\n', 'banana\n', 'cherry\n', 'date\n']
for fruit in fruits:
f.write(fruit)
# Read it back one line at a time (memory-friendly for big files)
with open('words.txt') as f:
for line in f:
word = line.strip() # each line still carries its '\n'
if len(word) > 5:
print(f'Long fruit: {word}')
# Long fruit: banana
# Long fruit: cherry
For large files, you can loop directly over the file object. Python reads it lazily—one line at a time—so your program doesn't load megabytes of text into RAM all at once.