Featured Post

Python Set Operations Explained: From Theory to Real-Time Applications

Image
A  set  in Python is an unordered collection of unique elements. It is useful when storing distinct values and performing operations like union, intersection, or difference. Real-Time Example: Removing Duplicate Customer Emails in a Marketing Campaign Imagine you are working on an email marketing campaign for your company. You have a list of customer emails, but some are duplicated. Using a set , you can remove duplicates efficiently before sending emails. Code Example: # List of customer emails (some duplicates) customer_emails = [ "alice@example.com" , "bob@example.com" , "charlie@example.com" , "alice@example.com" , "david@example.com" , "bob@example.com" ] # Convert list to a set to remove duplicates unique_emails = set (customer_emails) # Convert back to a list (if needed) unique_email_list = list (unique_emails) # Print the unique emails print ( "Unique customer emails:" , unique_email_list) Ou...

3 Best Methods to Read Files in Python

Read file line by line

Python supports three specific methods to read files- read, readline, readlines. All these you use on files. Each has its unique purpose. Below are the best examples.

3 Methods to read file

  1. read
  2. readline
  3. readlines

Method-1: read

It reads records from file in sequence.

Here, file.txt is sample file with single row.

file.txt


abcdefghijk

file_object.read(2) ==> you will get 'ab'

file_object.read(4)  ===> you will get 'cdef'


Here, the multiple read methods read the data in sequence. The read(x) method will read only the number of characters that mentioned in the read method. Again, if you give multiple read methods then it will read in sequence.


Method-2: readline


It reads the file line by line.

Here, file.txt is a file with single row.

file.txt

abcdefghijk

file_object.readline() ==> you will get 'abcdefghijk'

Here, it reads the file line by line.


Method-3: readlines

It reads all the records at a time.

Here, file.txt is a file with two rows.

file.txt

abcdefghijk
iiiooooooia

file_object.readlines() ==> you will get both the lines.


abcdefghijk
iiiooooooia

Here, it reads all the lines at a time.

Summary

  • I've demonstrated three methods
  • Useful for interviews and projects

Comments

Popular posts from this blog

SQL Query: 3 Methods for Calculating Cumulative SUM

Big Data: Top Cloud Computing Interview Questions (1 of 4)

5 SQL Queries That Popularly Used in Data Analysis