+91 81900 98289

Python Read Files

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

read() returns the whole file as one string. readline() returns one line. A for loop over the file yields lines without loading a huge file as a list first.

Always decide the encoding. encoding=\"utf-8\" avoids a surprise on another computer.

Example 1: Start here

On disk, the same loop is: for line in open(path, encoding=\"utf-8\"). Prefer with.

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

Example 2: The whole text

read() on a real file returns one string, just like sample here.

sample = "Python\nSQL\n" # text print(sample)

Example 3: One line at a time

A for loop over a file yields one line per pass.

for line in "Python\nSQL\n".splitlines(): # repeat the indented lines once per value print(line)

Example 4: Strip the line ending

strip removes the newline that readlines keeps at the end of each line.

for line in ["Python\n", "SQL\n"]: # repeat the indented lines once per value print(line.strip()) # spaces at both ends are removed
On disk, the same loop is: for line in open(path, encoding=\"utf-8\"). Prefer with.
Call Now 81900 98289