Posts

Showing posts with the label Reading Files

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

Image
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 read readline 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 f ile_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 ab...