File I/O

File I/O

Reading a file

python
with open(\"data.txt\", \"r\") as f: content = f.read()

open(\"data.txt\", \"r\") opens for reading. The with block closes the file when done, even if an error occurs.

Read line by line:

python
with open(\"data.txt\", \"r\") as f: for line in f: print(line.strip())

Writing a file

python
with open(\"output.txt\", \"w\") as f: f.write(\"Hello, file!\n\")

Mode \"w\" overwrites. Use \"a\" to append.

Paths and errors

Use pathlib for cross-platform paths:

python
from pathlib import Path p = Path(\"data\") / \"file.txt\"

If the file does not exist, open raises FileNotFoundError. Handle with try/except if needed.

You have completed the Python Fundamentals track. Finish this lesson to earn your certificate.