Why files matter
Think of a file as a sticky note on your monitor. While your program runs, its variables live in RAM, the computer's short-term memory: fast, but wiped when the program ends. 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')
# Here, the file is closed for you,
# even if an error happened 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': adds to the end (and makes
# the file if it isn't there yet)
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
with open('log.txt', 'w') as f:
f.write('line one\nline two\n')
# .read(): the whole file as one string
with open('log.txt') as f:
text = f.read()
print(text)
# .readlines(): a list, one string per line
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
fruits = ['apple', 'banana', 'cherry', 'date']
with open('words.txt', 'w') as f:
for fruit in fruits:
f.write(fruit + '\n')
# Read it back one line at a time
with open('words.txt') as f:
for line in f:
word = line.strip() # drop the '\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 memory all at once.