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 : 03 Jan, 2021
Summarize
Comments
Improve
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 key.
- items() method to get the collection of all key-value pairs and iterate over it to read all keys — value pair from the properties.
- The file contains key-value pairs in each line (i.e it is a dictionary in python). This operator equals (=) works as a delimiter between the key and value
We will use this properties file(example.properties) for demonstration:
Example 1: Printing all propertiesdetails.
Approach:
- Import the module
- Load the properties file into our properties object.
- Here items() method is to get the collection of the tuple, Which contains Keys and Corresponding PropertyTuple values
Below is the implementation:
Python3
from
jproperties
import
Properties
configs
=
Properties()
with
open
(
'example.properties'
,
'rb'
) as read_prop:
configs.load(read_prop)
prop_view
=
configs.items()
print
(
type
(prop_view))
for
item
in
prop_view:
print
(item)
Output:
Output Of The Program Using items() Method
Example 2: Printing properties file In the basis of key, values pairs like in dictionary in Python
Approach:
- Import the module
- Then we open the .properties file in ‘rb’ mode then we use load() function
- Then we use items() method to get the collection all key-value pairs here (i.e: print(type(prop_view)) prints the class type of the argument specified
Below is the full implementation:
Python3
from
jproperties
import
Properties
configs
=
Properties()
with
open
(
'example.properties'
,
'rb'
) as read_prop:
configs.load(read_prop)
prop_view
=
configs.items()
print
(
type
(prop_view))
for
item
in
prop_view:
print
(item[
0
],
'='
, item[
1
].data)
Output:
Example 3: Printing each specific values-data as we need
Approach:
- Import the module
- Then we open the .properties file in ‘rb’ mode then we use load() function
- Use the get() method to return the value of the item with the specified key.
- Use len() function to get the count of properties of the file.
Below is the full implementation:
Python3
from
jproperties
import
Properties
configs
=
Properties()
with
open
(
'example.properties'
,
'rb'
) as read_prop:
configs.load(read_prop)
print
(configs.get(
"DB_User"
))
print
(f
'Database User: {configs.get("DB_User").data}'
)
print
(f
'Database Password: {configs["DB_PWD"].data}'
)
print
(f
'Properties Count: {len(configs)}'
)
Output:
Here Is The Output of Properties File Using get() Method
Please Login to comment...
Similar Reads
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
Read Only Properties in Python
Prerequisites: Python Classes and Objects A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. To put it in simple words, let us assume a class Student, a
2 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
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
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
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 begin with the 0th index. There are various ways
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 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 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
Python - Read blob object in python using wand library
BLOB stands for Binary Large OBject. A blob is a data type that can store binary data. This is different than most other data types used in databases, such as integers, floating point numbers, characters, and strings, which store letters and numbers. BLOB is a large complex collection of binary data which is stored in Database. Basically BLOB is us
2 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
How to convert PDF file to Excel file using Python?
In this article, we will see how to convert a PDF to Excel or CSV File Using Python. It can be done with various methods, here are we are going to use some methods. Method 1: Using pdftables_api Here will use the pdftables_api Module for converting the PDF file into any other format. It's a simple web-based API, so can be called from any programmin
2 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to create a duplicate file of an existing file using Python?
In this article, we will discuss how to create a duplicate of the existing file in Python. Below are the source and destination folders, before creating the duplicate file in the destination folder. After a duplicate file has been created in the destination folder, it looks like the image below. For automating of copying and removal of files in Pyt
5 min read
How to convert a PDF file to TIFF file using Python?
This article will discover how to transform a PDF (Portable Document Format) file on your local drive into a TIFF (Tag Image File Format) file at the specified location. We'll employ Python's Aspose-Words package for this task. The aspose-words library will be used to convert a PDF file to a TIFF file. Aspose-Words: Aspose-Words for Python is a pot
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(); } }, }); });