Introduction
Reading file data lets your program get information stored in files. This helps your program use or show data saved earlier.
Jump into concepts and practice - no test required
Reading file data lets your program get information stored in files. This helps your program use or show data saved earlier.
with open('filename.txt', 'r') as file: data = file.read()
open() opens the file. 'r' means read mode.
with makes sure the file closes automatically after reading.
with open('example.txt', 'r') as file: content = file.read()
with open('example.txt', 'r') as file: lines = file.readlines()
file = open('example.txt', 'r') content = file.read() file.close()
This program first writes two lines to a file, then reads and prints them.
with open('sample.txt', 'w') as f: f.write('Hello\nWorld!') with open('sample.txt', 'r') as f: data = f.read() print(data)
Always use with to open files to avoid forgetting to close them.
Reading large files with read() can use a lot of memory; consider reading line by line.
Use open() with mode 'r' to read files.
with helps manage file closing automatically.
You can read whole files or line by line depending on your need.
open('file.txt', 'r') command do in Python?open() function is used to open a file in a specified mode.with?open(filename, mode) as variable to assign the file object.file.read() reads all content.with open('example.txt', 'r') as f:
lines = f.readlines()
print(lines)readlines() reads all lines into a list, each line ending with a newline character '\n' except possibly the last.file = open('notes.txt', 'r')
for line in file.read():
print(line)
file.close()file.read() which returns a single string of the whole file content.file.readlines() or iterate directly on file.line.strip() removes spaces and newline characters from both ends. The condition if line.strip() filters out empty lines.