0% found this document useful (0 votes)
5 views20 pages

Unit IV Python

The document discusses various file types in Python, categorizing them into text and binary files, and details how to read from and write to text files using built-in functions like open(), read(), readline(), and writelines(). It also covers algorithms that utilize file-reading techniques, methods for transferring files over the internet, and data storage using sets, tuples, and dictionaries. Additionally, it explains the use of the 'in' operator for checking membership in tuples and sets.

Uploaded by

yasothapriya.m
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views20 pages

Unit IV Python

The document discusses various file types in Python, categorizing them into text and binary files, and details how to read from and write to text files using built-in functions like open(), read(), readline(), and writelines(). It also covers algorithms that utilize file-reading techniques, methods for transferring files over the internet, and data storage using sets, tuples, and dictionaries. Additionally, it explains the use of the 'in' operator for checking membership in tuples and sets.

Uploaded by

yasothapriya.m
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT IV

KINDS OF FILES IN PYTHON


Python interacts with various file types, categorized primarily as text files
and binary files.
 Text Files:
These files store data as human-readable characters. Each line typically
ends with a special character denoting the end-of-line (EOL), which
defaults to a newline
character ("\n") in Python. Common text file types include:
o .txt: Plain text files for general text storage.
o .csv: Comma-separated values files for tabular data.
o .log: Log files for recording events.
o .ini: Configuration files storing settings in key-value pairs.
o .py: Python source code files.
o .json: JavaScript Object Notation files for data interchange.
o .yaml: Human-readable data serialization format.
o .html: Hypertext Markup Language for web pages.
 Binary Files:
These files store data in binary format (0s and 1s), not directly human-
readable. They require specific programs or software to interpret their
content. Examples include:
o Images (.jpg, .png, .gif, etc.)
o Audio files (.mp3, .wav, etc.)
o Video files (.mp4, .avi, etc.)
o Executable files (.exe, etc.)
o .pdf: Portable Document Format.
o .zip: Compressed archives.
o Pickle files: Serialized Python objects.

Python provides built-in functions to handle these file types, allowing


for operations such as creating, reading, writing, and modifying files. The

1
open()
function is central to file handling, accepting a file path and mode (e.g.,
read "r", write "w", append "a", binary "b") as arguments.

Opening a Text File


It is done using the open() function. No module is required to be imported
for this function.

Example: Here, file1 is created as an object for MyFile1 and file2 is


created as an object for MyFile2.

Read Text File


There are three ways to read a text file in Python:
 Using read()
 Using readline()
 Using readlines()

2
Reading From a File Using read()

 read(): Returns the read bytes in form of a string. Reads n


bytes, if no n specified, reads the entire file.

Reading a Text File Using readline()


readline(): Reads a line of the file and returns in form of a [Link]
specified n, reads at most n bytes. However, does not reads more than
one line, even if n
exceeds the length of the line.

Reading a File Using readlines()


readlines(): Reads all the lines and return them as each line a string
element in a list.

Example:

f1 = open("[Link]", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

[Link]("Hello \n")
[Link](L)
[Link]()

f1 = open("[Link]", "r+")

print("Output of read():")
print([Link]())
print()

[Link](0)
print("Output of readline():")
print([Link]())
print()

[Link](0)

3
print("Output of read(9):")
print([Link](9))
print()

[Link](0)
print("Output of readline(9):")
print([Link](9))
print()

[Link](0)
print("Output of readlines():")
print([Link]())
print()

[Link]()

Output
Output of read():
Hello
This is Delhi
This is Paris
This is London
Output of readline():
Hello
Output of read(9):
Hello
Th
Output of readline(9):
Hello
Output of readlines():
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Write to Text File in Python


There are two ways to write in a file:
 Using write()
 Using writelines()
Writing to a Python Text File Using write()

 write(): Inserts the string str1 in a single line in the text file.

4
Output:
Enter the name of the employee: ram
Enter the name of the employee:
kiran Enter the name of the
employee: arun Data is written into
the file.

5
Writing to a Text File Using writelines()
writelines(): For a list of string elements, each string is inserted in the
text [Link] to insert multiple strings at a single time.

Output:
Enter the name of the employee:
ram Enter the name of the
employee: kiran Enter the name of
the employee: arun Data is written

into the file.

6
Appending to a File in Python
 In this example, a file named "[Link]" is initially opened in
write mode ( "w" ) to write lines of text.
 The file is then reopened in append mode ( "a" ), and "Today" is
added to the existing content.
 The output after appending is displayed using readlines .
 Subsequently, the file is reopened in write mode, overwriting the
content with "Tomorrow". The final output after writing is displayed
using readlines.
Example:
file1 = open("[Link]", "w")
L = ["Welcome to GFGC NAREGAL \n", "To Study BCA \n", "This is Best
College\n"] [Link](L)
[Link]()
# Append-adds at last
file1 = open("[Link]", "a") # append
mode [Link]("Today \n")
[Link]()
file1 = open("[Link]", "r")
print("Output of Readlines after appending")
print([Link]())
print()
[Link]()
# Write-Overwrites
file1 = open("[Link]", "w") # write mode
[Link]("Tomorrow \n")
[Link]()

file1 = open("[Link]", "r")


print("Output of Readlines after writing")
print([Link]())
7
print()
[Link]()
Output:
Output of Readlines after appending
['Welcome to GFGC NAREGAL \n', 'To Study BCA \n', 'This is Best College\
n', 'Today
\n']
Output of Readlines after writing
['Tomorrow \n']

Closing a Text File in Python


 Python close() function closes the file and frees the memory space
acquired by that file.
 It is used at the time when the file is no longer needed or if it is to
be opened in a different file mode.

Syntax:
File_object.close()

Example:

8
ALGORITHMS THAT USE THE FILE-READING TECHNIQUES IN
PYTHON
Several algorithms utilize file-reading techniques in Python, often
depending on the specific task and data structure. Some common
examples include:
 Data analysis and processing:
Algorithms designed for data analysis frequently read data from files. For
example, a program analyzing customer purchase history might read
data from a CSV file, process it, and then output insights. Libraries like
Pandas are often used for this purpose, providing efficient ways to read
and manipulate data from various file formats.
 Search algorithms:
Algorithms that search for specific patterns or information within a file,
such as finding a particular word or phrase in a text file, rely on file
reading. These algorithms may read the entire file into memory or
process it line by line, depending on the size and structure of the file.
 Sorting algorithms:
When dealing with large datasets that cannot fit into memory, sorting
algorithms may read data from a file in chunks, sort each chunk, and
then merge the sorted chunks to produce a fully sorted output. This
approach is known as external sorting.
 Text processing algorithms:
Algorithms that perform text analysis, such as natural language
processing tasks, often read text from files. These algorithms may involve
tokenizing the text, counting word frequencies, or identifying specific
grammatical structures.
 Configuration file parsing:
Many applications use configuration files to store settings and
parameters. Algorithms that parse these files read the data and use it to
configure the application's behaviour. Common file formats for
configuration files include JSON, YAML, and INI.
 Data validation and cleaning:
Algorithms designed to validate and clean data often read data from files,
check for errors or inconsistencies, and then output a corrected version of
the data. This process may involve checking data types, removing
duplicates, or handling missing values.

9
FILES OVER THE INTERNET IN PYTHON
Transferring files over the internet in Python can be achieved through
several methods, each suitable for different scenarios:
[Link] the requests library (HTTP)
The requests library is a versatile tool for making HTTP requests,
including downloading and uploading files.

[Link] [Link]
The [Link] module provides functions for fetching data across the
web.

10
[Link] FTP (ftplib)
For interacting with FTP servers, Python's ftplib module can be utilized.

[Link] programming
For more control over the transfer process, you can use sockets to
establish a connection and send/receive data.

11
Handling large files
For large files, reading and sending data in chunks can be more efficient.

12
MULTILINE RECORDS IN PYTHON
1) Using writelines() Function
This function writes several string lines to a text file simultaneously. An
iterable Object, such as a list, set, tuple, etc., can be sent to the
writelines() method.
Syntax

Example - 1

Output
Example - 2

Output
Welcome to TutorialsPoint
Write multiple lines
Done successfully

13
2)Using while
loop
Example - 3:

Output
Welcome to TutorialsPoint:
The next line is printed successfully:

STORING DATA USING SETS


 Python also includes a data type for sets.
 A set is an unordered collection with no duplicate elements.
 Basic uses include membership testing and eliminating duplicate entries.
 Curly braces or the set() function can be used to create sets.
Example:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}


print(basket)
Output:
{'orange', 'banana', 'pear', 'apple'}

'orange' in basket #True


-This checks for membership. Since 'orange' is in the set, it returns True [1].

14
'crabgrass' in basket #False

# Demonstrate set operations on unique letters from two words

a = set('abracadabra')
b = set('alacazam')
a
{'a', 'r', 'b', 'c', 'd'}
a-b
{'r', 'd', 'b'}
a|b
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a&b
{'a', 'c'}
a^b
{'r', 'd', 'b', 'm', 'z', 'l'}

STORING DATA USING TUPLES


 A tuple consists of a number of values separated by commas.
 Tuples may seem similar to lists, they are often used in different situations
and for different purposes.
 Tuples are immutable, Cannot be modified after creation and usually
contain a heterogeneous sequence of elements that are accessed via
unpacking or indexing.
 Lists are mutable, Can add, remove, or change items and their elements are
usually homogeneous and are accessed by iterating over the list.
t = (12345, 54321, 'hello!')
print(t[0])
output:
12345
print(t)
output:
(12345, 54321, 'hello!')
t = (12345, 54321, 'hello!')
u = t,(1, 2, 3, 4, 5)
print(u)
output:
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# Tuples are immutable:

15
t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v
output:
([1, 2, 3], [3, 2, 1])

STORING DATA USING DICTIONARIES


 It is best to think of a dictionary as a set of key: value pairs, with the requirement that
the keys are unique (within one dictionary).
 A pair of braces creates an empty dictionary: {}.
 Placing a comma-separated list of key:value pairs within the braces adds initial
key:value pairs to the dictionary; this is also the way dictionaries are written on output.

Example:

tel = {'jack': 4098, 'sape': 4139}


tel['guido'] = 4127
print(tel)
{'jack': 4098, 'sape': 4139, 'guido': 4127}
tel['jack']
4098
tel['irv']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'irv'
print([Link]('irv'))
None
del tel['sape']
tel['irv'] = 4127
tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
list(tel)
['jack', 'guido', 'irv']
sorted(tel)
['guido', 'irv', 'jack']

16
'guido' in tel
True
'jack' not in tel
False

INVERTING A DICTIONARY
Dictionary is a collection which is unordered, changeable and indexed. In Python,
dictionaries are written with curly brackets, and they have keys and values.
# Python code to demonstrate
# how to invert mapping
# using dict comprehension

# initialising dictionary
ini_dict = {101: "akshat", 201 : "ball"}

# print initial dictionary


print("initial dictionary : ", str(ini_dict))

# inverse mapping using dict comprehension


inv_dict = {v: k for k, v in ini_dict.items()}

# print final dictionary


print("inverse mapped dictionary : ", str(inv_dict))
Output:
initial dictionary : {201: 'ball', 101: 'akshat'}
inverse mapped dictionary : {'ball': 201, 'akshat': 101}

USING THE IN OPERATOR ON TUPLES


In Python, the in operator is a membership operator used to determine if a specific
value exists within a tuple.
It returns a boolean value: True if the item is found and False otherwise.
Syntax:
value in tuple_name.
Complementary Operator:
You can use not in to check if a value is absent from a tuple.
Exact Matching:
The check requires an exact match of both value and data type
(e.g., 5 in ("5",6) is False because the integer 5 does not match the string "5").
Examples
Basic Presence Check:
fruits = ("apple", "banana", "cherry")
print("apple" in fruits) # Output: True
17
print("orange" in fruits) # Output: False
Using with if Statements:
The most common use case is to control program flow based on membership.
if "banana" in fruits:
print("Yes, banana is available.")
Absence Check:

colors = ("red", "blue")


print("green" not in colors) # Output: True

USING THE IN OPERATOR ON SETS


The in operator in Python is a membership operator used to check if a specific element
exists within a set.
The expression x in s returns True if element x is present in set s,
and False otherwise.

Examples
Basic Check:
fruits = {"apple", "banana", "cherry"}

print("apple" in fruits) # Output: True

print("grape" in fruits) # Output: False


Negation with not in:
numbers = {1, 2, 3, 4, 5}

print(10 not in numbers) # Output: True


Conditional Logic: The Python in operator is commonly used in if statements to control
program flow based on existence.

required_permissions = {"read", "write", "execute"}


user_action = "delete"
if user_action in required_permissions:
print("Action allowed")
else:
print("Access denied") # This will execute

USING THE IN OPERATOR ON DICTIONARIES


The in operator in Python is a membership operator used to check for the presence of a
key in a dictionary. It returns True if the key exists and False otherwise.

Basic Usage: Checking for Keys


By default, using the in operator directly on a dictionary checks its keys.
Syntax:
key in dictionary
18
Example:
my_dict = {"name": "Alice", "age": 25}
print("name" in my_dict) # Output: True
print("Alice" in my_dict) # Output: False (checks keys, not values)

Checking for Values or Items


To check for membership in other parts of the dictionary, use specific dictionary methods:
Values: Use the values() method to check if a specific value exists.
if "Alice" in my_dict.values():
Key-Value Pairs: Use the items() method to check for a specific pair, usually represented as
a tuple (key, value).
if ("name", "Alice") in my_dict.items():
The not in Operator
The not in operator is the logical negation of in, returning True if the key is not present.
Example: if "email" not in my_dict:
Related Keyword: in in For Loops
The in keyword is also used as part of the syntax for for loops to iterate over dictionary
keys.
Example: for key in my_dict:

COMPARING COLLECTIONS
Comparing collections in Python depends on whether you care about the order of elements
or the frequency of duplicates.
1. Identity vs. Equality
== (Equality): Checks if two collections have the same content.
is (Identity): Checks if both variables point to the exact same object in memory.
2. Comparing Lists and Tuples (Ordered)
Exact Match: Use the == operator. It returns True only if elements match in both
content and sequence.
Ignore Order, Keep Duplicates: Use the [Link] class. It creates a
frequency map, making it ideal for checking if two lists are anagrams.
Ignore Order and Duplicates: Convert both to sets and use ==. This checks if they
contain the same unique elements.

3. Comparing Sets (Unordered, Unique)


Sets are designed for membership and comparison operations:
set1 == set2: Returns True if both contain the exact same unique items.
Difference (-): Returns items in the first set but not the second.
Intersection (&): Returns items present in both sets.
Symmetric Difference (^): Returns items in either set, but not both.
19
4. Comparing Dictionaries
==: Returns True if both dictionaries have the same keys and each key has the same
value. Order generally does not matter for equality.

20

You might also like