+91 81900 98289

Python File Handling

This Python File Handling lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

open reads or writes a file. The mode \"r\" reads text, \"w\" writes and clears the file, and \"a\" adds to the end.

A with block closes the file even when an error happens. That is the form to use.

Start here

This browser runner has no project folder, so file demos stay small here.

from pathlib import Path # load a tool that comes with Python print(Path("notes.txt").name) print("Use with open(...) as handle on your machine.")

Read lines from text

splitlines is the same shape as looping over a file. The browser runner has no project folder, so the sample stays in a string.

sample = "Python\nSQL\n" # text print(sample.splitlines()) # one list item for each line

Build the text you would write

On your computer, write this text inside a with open(path, \"w\", encoding=\"utf-8\") block.

lines = ["name=Asha\n", "city=Chennai\n"] # a list; the values stay in this order print("".join(lines)) # join the pieces into one text

Use a memory file

StringIO behaves like a file but keeps the text in memory, so this page can run it.

import io # load a tool that comes with Python handle = io.StringIO() # one object handle.write("Python\n") print(handle.getvalue())
This browser runner has no project folder, so file demos stay small here.