Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
Reading files in Python is a common task, and the built-in open()
function makes it easy to do. In this tutorial, you'll learn different ways to read a file in Python.
To read the entire contents of a file, you can use the read()
method. This method returns the file's contents as a single string.
# Open the file for reading with open('path/to/your/file.txt', mode='r') as file: # Read the entire contents of the file file_contents = file.read() # Print the file's contents print(file_contents)
If you're working with a large file or you only need to process the file one line at a time, you can use a for
loop to iterate over the file object. This approach reads the file line by line, which is more memory-efficient for large files.
# Open the file for reading with open('path/to/your/file.txt', mode='r') as file: # Iterate over the file object line by line for line in file: # Print each line print(line.strip())
The strip()
method is used to remove leading and trailing whitespace characters, including the newline character at the end of each line.
To read a specific number of lines from the file, you can use the readline()
method inside a loop.
num_lines = 3 # Open the file for reading with open('path/to/your/file.txt', mode='r') as file: # Read the specified number of lines for _ in range(num_lines): line = file.readline() print(line.strip())
If you want to read all lines of a file into a list, you can use the readlines()
method.
# Open the file for reading with open('path/to/your/file.txt', mode='r') as file: # Read all lines into a list lines = file.readlines() # Iterate over the list and print each line for line in lines: print(line.strip())
Alternatively, you can use the built-in list()
function to achieve the same result:
with open('path/to/your/file.txt', mode='r') as file: lines = list(file) for line in lines: print(line.strip())
Remember to use the with
statement when working with files, as it ensures that the file is properly closed and resources are released after you finish reading the file.
Reading text file in Python:
open()
function to read a text file in Python.file_path = 'example.txt' # Read text file with open(file_path, 'r') as file: content = file.read() print(content)
Read entire file in Python:
file_path = 'example.txt' # Read entire file with open(file_path, 'r') as file: content = file.read() print(content)
Python read file line by line:
file_path = 'example.txt' # Read file line by line with open(file_path, 'r') as file: for line in file: print(line.strip()) # Remove newline characters
File input/output in Python:
# Writing to a file with open('output.txt', 'w') as file: file.write('Hello, World!\n') # Reading from a file with open('input.txt', 'r') as file: content = file.read() print(content)
Reading CSV files in Python:
csv
module to read data from a CSV file.import csv csv_file_path = 'example.csv' # Read CSV file with open(csv_file_path, 'r') as csv_file: reader = csv.reader(csv_file) for row in reader: print(row)
Binary file reading in Python:
binary_file_path = 'binary_file.bin' # Read binary file with open(binary_file_path, 'rb') as binary_file: content = binary_file.read() print(content)
Python read file into list:
file_path = 'example.txt' # Read file into a list with open(file_path, 'r') as file: lines = file.readlines() print(lines)
Reading JSON files in Python:
import json json_file_path = 'example.json' # Read JSON file with open(json_file_path, 'r') as json_file: data = json.load(json_file) print(data)
Read specific lines from a file in Python:
file_path = 'example.txt' lines_to_read = [1, 3, 5] # Read specific lines from file with open(file_path, 'r') as file: for line_number, line in enumerate(file, 1): if line_number in lines_to_read: print(line.strip())
Python file read modes:
file_path = 'example.txt' # Read file in different modes with open(file_path, 'r') as file: content = file.read() print(content) with open(file_path, 'rb') as file: binary_content = file.read() print(binary_content)
Read and parse XML files in Python:
xml.etree.ElementTree
to read and parse XML files.import xml.etree.ElementTree as ET xml_file_path = 'example.xml' # Read and parse XML file tree = ET.parse(xml_file_path) root = tree.getroot() for element in root: print(element.tag, element.text)
Reading and processing large files in Python:
file_path = 'large_file.txt' chunk_size = 1024 # Read large file in chunks with open(file_path, 'r') as file: while True: chunk = file.read(chunk_size) if not chunk: break process_chunk(chunk)
Reading Excel files in Python:
pandas
to read Excel files in Python.import pandas as pd excel_file_path = 'example.xlsx' # Read Excel file df = pd.read_excel(excel_file_path) print(df)
Python read file from URL:
urllib
.import urllib.request url = 'https://example.com/example.txt' # Read file from URL with urllib.request.urlopen(url) as response: content = response.read().decode('utf-8') print(content)
Read and extract data from log files in Python:
import re log_file_path = 'example.log' # Read and extract data from log file with open(log_file_path, 'r') as log_file: for line in log_file: match = re.search(r'Error: (.+)', line) if match: error_message = match.group(1) print(f"Error: {error_message}")
Unicode file reading in Python:
file_path = 'unicode_file.txt' # Read Unicode file with open(file_path, 'r', encoding='utf-8') as file: content = file.read() print(content)
Error handling when reading files in Python:
file_path = '/path/to/nonexistent_file.txt' try: # Try to read file with open(file_path, 'r') as file: content = file.read() print(content) except FileNotFoundError: print(f"File not found: {file_path}")
Reading and processing CSV data in Python:
csv
module.import csv csv_file_path = 'example.csv' # Read and process CSV data with open(csv_file_path, 'r') as csv_file: reader = csv.reader(csv_file) for row in reader: process_row(row)
Python read file and count occurrences:
file_path = 'example.txt' word_to_count = 'Python' # Read file and count occurrences with open(file_path, 'r') as file: content = file.read() count = content.count(word_to_count) print(f"The word '{word_to_count}' occurs {count} times.")