Skip to content
- Tutorials
- Python Tutorial
- Taking Input in Python
- Python Operators
- Python Data Types
- Python Loops and Control Flow
- Python Functions
- Python OOPS Concept
- Python Data Structures
- Python Exception Handling
- Python File Handling
- Python Exercises
- Java
- Java Programming Language
- Java Collections
- Java 8 Tutorial
- Java Programs
- Java Interview Questions
- Java Exercises
- Java Quiz
- Java Projects
- Advance Java
- Programming Languages
- System Design
- Interview Corner
- Computer Science Subjects
- DevOps
- Linux
- Software Testing
- Databases
- Android
- Excel
- Mathematics
- Python Tutorial
- DSA
- Data Structures
- Algorithms
- Analysis of Algorithms
- Searching Algorithms
- Sorting Algorithms
- Greedy Algorithms
- Dynamic Programming
- Graph Algorithms
- Pattern Searching
- Recursion
- Backtracking
- Divide and Conquer
- Mathematical Algorithms
- Geometric Algorithms
- Bitwise Algorithms
- Randomized Algorithms
- Branch and Bound
- Algorithms Tutorial
- DSA Tutorial
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top Interview Questions
- Puzzles
- Data Science
- Web Tech
- Courses
-
Last Updated : 21 Mar, 2024
Summarize
Comments
Improve
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 begin with the 0th index. There are various ways to read specific lines from a text file in python, this article is aimed at discussing them.
Method 1: fileobject.readlines()
A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously. It can be easily used to print lines from any random starting index to some ending index. It initially reads the entire content of the file and keep a copy of it in memory. The lines at the specified indices are then accessed.
Example:
Python3
# open the sample file used
file
=
open
(
'test.txt'
)
# read the content of the file opened
content
=
file
.readlines()
# read 10th line from the file
print
(
"tenth line"
)
print
(content[
9
])
# print first 3 lines of file
print
(
"first three lines"
)
print
(content[
0
:
3
])
Output
tenth line
This is line 10.
first three lines
This is line 1.This is line 2.This is line 3.
Method 2: linecache package
The linecache package can be imported in Python and then be used to extract and access specific lines in Python. The package can be used to read multiple lines simultaneously. It makes use of cache storage to perform optimization internally. This package opens the file on its own and gets to the particular line. This package has getline() method which is used for the same.
Syntax:
getLine(txt-file, line_number)
Example:
Python3
# importing required package
import
linecache
# extracting the 5th line
particular_line
=
linecache.getline(
'test.txt'
,
4
)
# print the particular line
print
(particular_line)
Output :
This is line 5.
Method 3: enumerate()
The enumerate() method is used to convert a string or a list object to a sequence of data indexed by numbers. It is then used in the listing of the data in combination with for loop. Lines at particular indexes can be accessed by specifying the index numbers required in an array.
Example:
Python3
# open a file
file
=
open
(
"test.txt"
)
# lines to print
specified_lines
=
[
0
,
7
,
11
]
# loop over lines in a file
for
pos, l_num
in
enumerate
(
file
):
# check if the line number is specified in the lines to read array
if
pos
in
specified_lines:
# print the required line number
print
(l_num)
Output
This is line 1.This is line 8.This is line 12.
Please Login to comment...
Similar Reads
Python - Convert simple lines to bulleted lines using the Pyperclip module
Pyperclip is the cross-platform Python module which is used for copying and pasting the text to the clipboard. Let's suppose you want to automate the task of copying the text and then convert them to the bulleted points. This can be done using the pyperclip module. Consider the below examples for better understanding. Examples: Clipboard Content :
2 min read
Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt 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). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
Count number of lines in a text file in Python
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, If the file is small, you can use readlines() or a loop approach in Python. Input: line 1 line 2 line 3 Output: 3 Explanation: The Input has 3 number of line in
3 min read
Eliminating repeated lines from a file using Python
Let us see how to delete several repeated lines from a file using Python's File Handling power. If the file is small with a few lines, then the task of deleting/eliminating repeated lines from it could be done manually, but when it comes to large files, this is where Python comes to your rescue. Eliminating repeated lines from a file in PythonBelow
6 min read
How to count the number of lines in a CSV file in Python?
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the n
2 min read
Replace Commas with New Lines in a Text File Using Python
Replacing a comma with a new line in a text file consists of traversing through the file's content and substituting each comma with a newline character. In this article, we will explore three different approaches to replacing a comma with a new line in a text file. Replace Comma With a New Line in a Text FileBelow are the possible approaches to rep
2 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
How to read from a file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line
5 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
Read List of Dictionaries from File in Python
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. Read a List of Dictionary from Text Files in PythonUsing Pickle ModuleUsing read( ) MethodThe problem s
3 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.literal_eval() method : Function safer than the ev
2 min read
Read Properties File Using jproperties in Python
In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal. pip install jproperties Various properties of this module: get() Method or Index-Based access to reading the values associated with the ke
2 min read
How to read a numerical data or file in Python with numpy?
Prerequisites: Numpy NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different formats of file : The data can be saved in a txt file wh
4 min read
Python - Read file from sibling directory
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__Sibling_1: | \__demo.py | |__Sibling_2: | \__file.t
3 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 variable called data. after that we replace the end of t
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 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 As String In PythonBelow are some of the approach
3 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 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 without newlines in Python. Read a file without newl
2 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that 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. Learning Ef
7 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
4 min read
Find line number of a specific string or substring or word from a .txt file in Python
Finding the line number of a specific string and its substring is a common operation performed by text editors or any application with some level of text processing capabilities. In this article, you will learn how to find line number of a specific string or substring or word from a .txt (plain text) file using Python. The problem in hand could be
4 min read
Retrieve A Specific Element In a Csv File using Python
We have given a file and our task is to retrieve a specific element in a CSV file using Python. In this article, we will see some generally used methods for retrieving a specific element in a CSV file. Retrieve a Specific Element in a CSV File Using PythonBelow are some of the ways by which we can retrieve a specific element in a CSV file using Pyt
2 min read
Read a zipped file as a Pandas DataFrame
In this article, we will try to find out how can we read data from a zip file using a panda data frame. Why we need a zip file? People use related groups of files together and to make files compact, so they are easier and faster to share via the web. Zip files are ideal for archiving since they save storage space. And, they are also useful for secu
2 min read
How to read a CSV file to a Dataframe with custom delimiter in Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use th
3 min read
How to read csv file with Pandas without header?
Prerequisites: Pandas A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. This article discusses how we can read a csv file without header using pandas. To do this header attribute should be set to None while reading the file. Syntax: read_csv("file name", header=None) ApproachImport
1 min read
Read Text file into PySpark Dataframe
In this article, we are going to see how to read text files in PySpark Dataframe. There are three ways to read text files into PySpark DataFrame. Using spark.read.text()Using spark.read.csv()Using spark.read.format().load() Using these we can read a single text file, multiple files, and all files from a directory into Spark DataFrame and Dataset. T
3 min read
PySpark - Read CSV file into DataFrame
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authorsbook_authorbooksRead CSV File into DataFrame Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). C/C++ Code from pyspark.sql import
2 min read
Read File Without Saving in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article we will discuss how can we Read files without Saving them in Flask, we will also veri
2 min read
Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl d
3 min read
Article Tags :
Practice Tags :
Trending in News
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });