MyInternships.in

Python Files & Errors

Python Read and Write Files

Once a file is open, Python gives you several methods to pull data out of it or push data into it. This lesson covers the core read and write methods you will use constantly.


Reading a Whole File

The read() method returns the entire file content as one string. It is simple, but for large files it can use a lot of memory since everything loads at once.

read() the whole file
Python
f = open("notes.txt", "r")
text = f.read()
print(text)
f.close()

Reading Line by Line

readline() returns just one line each time you call it, including the trailing newline character. readlines() returns every line at once as a list of strings, which pairs nicely with a for loop.

readline() vs readlines()
Python
f = open("notes.txt", "r")
first_line = f.readline()
print(first_line)
f.close()

f = open("notes.txt", "r")
lines = f.readlines()
print(lines)   # ['Hello\n', 'World\n']
f.close()

The most Pythonic way to process a file, especially a large one, is to loop directly over the file object. Python reads it lazily, one line at a time, which is fast and memory-efficient.

Iterating over a file
Python
f = open("students.txt", "r")
for line in f:
    print(line.strip())
f.close()
💡

Use .strip() on each line to remove the trailing \n newline character before printing or storing it.

Writing to a File

write() sends one string to the file, and writelines() sends a list of strings in one go. Neither method adds newlines automatically, so include \n yourself where needed.

write() and writelines()
Python
f = open("output.txt", "w")
f.write("Line one\n")
f.write("Line two\n")
f.close()

lines = ["Apple\n", "Banana\n", "Cherry\n"]
f = open("fruits.txt", "w")
f.writelines(lines)
f.close()

Appending Instead of Overwriting

Open the file in "a" mode to add new content at the end without touching what is already there — perfect for logs or growing a data file over time.

Appending new data
Python
f = open("fruits.txt", "a")
f.write("Mango\n")
f.close()
MethodReturnsBest for
read()Whole file as one stringSmall files
readline()One line per callReading a header, then the rest
readlines()List of all linesWhen you need list operations like len()
for line in fileOne line per loop stepLarge files, memory efficient
write(text)Writes one stringSingle writes
writelines(list)Writes many stringsWriting a list of strings at once

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships