How to Read from a File in Python
Last Updated :
19 Dec, 2024
Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently.
Basic File Reading in Python
Basic file reading involves opening a file and reading its contents into your program. This can be done using the following built-in open() functions.
- open(“geeks.txt”, “r”): Opens the file example.txt in read mode.
- file.read(): Reads the entire content of the file.
- file.close(): Closes the file to free up system resources.
Example: Reading the Entire File
Python
# Open the file in read mode
file = open("geeks.txt", "r")
# Read the entire content of the file
content = file.read()
# Print the content
print(content)
# Close the file
file.close()
Output:
Hello World
Hello GeeksforGeeks
Line-by-Line Reading in Python
We may want to read a file line by line, especially for large files where reading the entire content at once is not practical. It is done with following two methods:
- for line in file: Iterates over each line in the file.
- line.strip(): Removes any leading or trailing whitespace, including newline characters.
Example: Using a Loop to Read Line by Line
Python
# Open the file in read mode
file = open("geeks.txt", "r")
# Read each line one by one
for line in file:
print(line.strip()) # .strip() to remove newline characters
# Close the file
file.close()
Output:
Hello World
Hello GeeksforGeeks
Using readline()
file.readline() reads one line at a time. while line continues until there are no more lines to read.
Python
# Open the file in read mode
file = open("geeks.txt", "r")
# Read the first line
line = file.readline()
while line:
print(line.strip())
line = file.readline() # Read the next line
# Close the file
file.close()
Output:
Hello World
Hello GeeksforGeeks
Reading Binary Files in Python
Binary files store data in a format not meant to be read as text. These can include images, executablesor any non-text data. We are using following methods to read binary files:
- open(“example.bin”, “rb”): Opens the file example.bin in read binary mode.
- file.read(): Reads the entire content of the file as bytes.
- file.close(): Closes the file to free up system resources.
Example: Reading a Binary File
Python
# Open the binary file in read binary mode
file = open("geeks.txt", "rb")
# Read the entire content of the file
content = file.read()
# Print the content (this will be in bytes)
print(content)
# Close the file
file.close()
Output:
b'Hello World\r\nHello GeeksforGeeks'
Reading Specific Parts of a File
Sometimes, we may only need to read a specific part of a file, such as the first few bytes, a specific line, or a range of lines.
Example: Reading the First N Bytes
Python
# Open the file in read mode
file = open("geeks.txt", "r")
# Read the first 10 bytes
content = file.read(10)
print(content)
# Close the file
file.close()
Output:
Hello World
file.read(10): Reads the first 10 bytes of the file.
Reading CSV Files in Python
Reading CSV (Comma-Separated Values) files are a common task for working with tabular data. Python’s csv module makes it easy to read CSV files.
Example: Using the csv Module
Python
import csv
# Open the CSV file
with open("example.csv", newline='') as csvfile:
# Create a CSV reader object
csvreader = csv.reader(csvfile)
# Read and print each row
for row in csvreader:
print(row)
Output:
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Dollars', 'H34', 'Total income per employee count', 'Financial ratios', '769,400', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Dollars', 'H35', 'Surplus per employee count', 'Financial ratios', '48,000', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H36', 'Current ratio', 'Financial ratios', 'C', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H37', 'Quick ratio', 'Financial ratios', 'C', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H38', 'Margin on sales of goods for resale', 'Financial ratios', '12', 'ANZSIC06 groups C211, C212, C213 and C214']
['2014', 'Level 3', 'CC71', 'Primary Metal and Metal Product Manufacturing', 'Percentage', 'H39', 'Return on equity', 'Financial ratios', '19', 'ANZSIC06 groups C211, C212, C213 and C214']
Reading JSON Files in Python
Reading JSON (JavaScript Object Notation) files are widely used for data interchange. Python’s json module provides methods to read JSON files.
Example: Using the json Module
Python
import json
# Open the JSON file
with open("sample1.json", "r") as jsonfile:
# Load the JSON data
data = json.load(jsonfile)
# Print the data
print(data)
Output:
{'fruit': 'Apple', 'size': 'Large', 'color': 'Red'}
Similar Reads
How to Read from a File in Python
Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently. Basic File Reading in PythonBasic file reading inv
4 min read
How to Read from a File in Python
Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently. Basic File Reading in PythonBasic file reading inv
4 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.
2 min read
How To Read .Data Files In Python?
Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
4 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers
3 min read
How to delete data from file in Python
When we no longer require data, we usually prefer to erase or delete it so that space can be used up by other data that is important to us. Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on fil
3 min read
How to get file size in Python?
We can follow different approaches to get the file size in Python. It's important to get the file size in Python to monitor file size or in case of ordering files in the directory according to file size. Method 1: Using getsize function of os.path module This function takes a file path as an argumen
3 min read
Read File As String in Python
Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File
3 min read
How to search a pickle file in Python?
Prerequisites: pickle file Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert
3 min read
How to read large text files in Python?
In this article, we will try to understand how to read a large text file using the fastest way, with less memory usage using Python. To read large text files in Python, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates
3 min read
Read a file without newlines in Python
When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file wi
2 min read
How to copy file in Python3?
Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Pyt
2 min read
Python - How to search for a string in text files?
In this article, we are going to see how to search for a string in text files using Python Example: string = "GEEK FOR GEEKS"Input: "FOR" Output: Yes, FOR is present in the given string. Text File for demonstration: Finding the index of the string in the text file using readline() In this method, we
2 min read
How to read multiple text files from folder in Python?
Prerequisite: File Handlingos Python is a strong language which is extremely capable even when it comes to file handling. In this article, we will learn how to read multiple text files from a folder using python. Approach: Import modulesAdd path of the folderChange directoryGet the list of a file fr
2 min read
How to read numbers in CSV files in Python?
Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel)
4 min read
How to read a JSON response from a link in Python?
There is a huge amount of data available on the web and most of them are in form of (JavaScript Object Notation) JSON. But it is difficult for humans to directly read and use it. To resolve this problem in python we have different libraries which help us to read the JSON data fetched from the web. T
2 min read
How to Read Text File Into List in Python?
In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variab
2 min read
Read a file line by line in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Example [GFGTABS] Python # O
4 min read
Read a file line by line in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Example [GFGTABS] Python # O
4 min read