0% found this document useful (0 votes)
3 views39 pages

Python Notes Unit-IV&V

Uploaded by

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

Python Notes Unit-IV&V

Uploaded by

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

Python programming

UNIT-IV
Lists: Creating a list -Access values in List-Updating values in Lists-
Nested lists -Basic list operations-List Methods. Tuples: Creating,
Accessing, Updating and Deleting Elements in a tuple – Nested tuples–
Difference between lists and tuples. Dictionaries: Creating, Accessing,
Updating and Deleting Elements in a Dictionary – Dictionary Functions
and Methods - Difference between Lists and Dictionaries.
LIST:
 The list contains a mix of integers (10, 20, 40), a string ("GfG") and
a boolean (True).
 The list is printed and individual elements are accessed using their
indexes (starting from 0).
 type(a[2]) confirms "GfG" is a str.
 type(a[4]) confirms True is a bool.

[Link] [Link]., [Link].,


Python programming

Creating a List
Here are some common methods to create a list:
Using Square Brackets
# List of integers
a = [1, 2, 3, 4, 5]

# List of strings
b = ['apple', 'banana', 'cherry']

# Mixed data types


c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)

Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Access values in List:
Using list() Constructor
We can also create a list by passing an iterable (like a string, tuple or
another list) to list() function.
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)

[Link] [Link]., [Link].,


Python programming

Output
[1, 2, 3, 'apple', 4.5]
Creating List with Repeated Elements
We can create a list with repeated elements using the multiplication
operator.
# Create a list [2, 2, 2, 2, 2]
a = [2] * 5

# Create a list [0, 0, 0, 0, 0, 0, 0]


b = [0] * 7

print(a)
print(b)

Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Accessing List Elements
Elements in a list can be accessed using indexing. Python indexes start
at 0, so a[0] will access the first element, while negative
indexing allows us to access elements from the end of the list. Like
index -1 represents the last elements of list.
a = [10, 20, 30, 40, 50]

# Access first element


print(a[0])

# Access last element


print(a[-1])

[Link] [Link]., [Link].,


Python programming

Output
10
50
Adding Elements into List
We can add elements to a list using the following methods:
 append(): Adds an element at the end of the list.
 extend(): Adds multiple elements to the end of the list.
 insert(): Adds an element at a specific position.
# Initialize an empty list
a = []

# Adding 10 to end of list


[Link](10)
print("After append(10):", a)

# Inserting 5 at index 0
[Link](0, 5)
print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the end


[Link]([15, 20, 25])
print("After extend([15, 20, 25]):", a)

Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
Updating Elements into List
We can change the value of an element by accessing it using its index.
a = [10, 20, 30, 40, 50]

[Link] [Link]., [Link].,


Python programming

# Change the second element


a[1] = 25
print(a)

Output
[10, 25, 30, 40, 50]
Removing Elements from List
We can remove elements from a list using:
 remove(): Removes the first occurrence of an element.
 pop(): Removes the element at a specific index or the last element
if no index is specified.
 del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]

# Removes the first occurrence of 30


[Link](30)
print("After remove(30):", a)

# Removes the element at index 1 (20)


popped_val = [Link](1)
print("Popped element:", popped_val)
print("After pop(1):", a)

# Deletes the first element (10)


del a[0]
print("After del a[0]:", a)

Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]

[Link] [Link]., [Link].,


Python programming

After del a[0]: [40, 50]


Iterating Over Lists
We can iterate the Lists easily by using a for loop or other iteration
methods. Iterating over lists is useful when we want to do some
operation on each item or access specific items based on certain
conditions. Let's take an example to iterate over the list using for loop.
Using for Loop
a = ['apple', 'banana', 'cherry']

# Iterating over the list


for item in a:
print(item)

Output
apple
banana
cherry
To learn various other methods, please refer to iterating over lists.
Nested Lists in Python
A nested list is a list within another list, which is useful for
representing matrices or tables. We can access nested elements by
chaining indexes.

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Access element at row 2, column 3

[Link] [Link]., [Link].,


Python programming

print(matrix[1][2])

Output
6
List Methods:
Python List methods
Python list methods are built-in functions that allow us to perform
various operations on lists, such as adding,
removing, or modifying elements. In this article, we’ll explore
all Python list methods with a simple example.
List Methods
Let's look at different list methods in Python:
 append(): Adds an element to the end of the list.
 copy(): Returns a shallow copy of the list.
 clear(): Removes all elements from the list.
 count(): Returns the number of times a specified element appears in
the list.
 extend(): Adds elements from another list to the end of the current
list.
 index(): Returns the index of the first occurrence of a specified
element.
 insert(): Inserts an element at a specified position.
 pop(): Removes and returns the element at the specified position (or
the last element if no index is specified).
 remove(): Removes the first occurrence of a specified element.
 reverse(): Reverses the order of the elements in the list.
 sort(): Sorts the list in ascending order (by default).
Examples of List Methods
append():
Syntax: list_name.append(element)
In the code below, we will add an element to the list.
a = [1, 2, 3]

[Link] [Link]., [Link].,


Python programming

# Add 4 to the end of the list


[Link](4)
print(a)

Output
[1, 2, 3, 4]
copy():
Syntax: list_name.copy()
In the code below, we will create a copy of a list
a = [1, 2, 3]

# Create a copy of the list


b = [Link]()
print(b)

Output
[1, 2, 3]
clear():
Syntax: list_name.clear()
In the code below, we will clear all elements from the list.
a = [1, 2, 3]

# Remove all elements from the list


[Link]()
print(a)

Output
[]
count():
Syntax: list_name.count(element)

[Link] [Link]., [Link].,


Python programming

In the code below, we will count the occurrences of a specific element in


the list.
a = [1, 2, 3, 2]

# Count occurrences of 2 in the list


print([Link](2))

Output
2
extend():
Syntax: list_name.extend(iterable)
In the code below, we will extend the list by adding elements from
another list.
a = [1, 2]

# Extend list a by adding elements from list [3, 4]


[Link]([3, 4])
print(a)

Output
[1, 2, 3, 4]
index():
Syntax: list_name.index(element)
In the code below, we will find the index of a specific element in the list.
a = [1, 2, 3]

# Find the index of 2 in the list


print([Link](2))

Output
1

[Link] [Link]., [Link].,


Python programming

insert():
Syntax: list_name.insert(index, element)
In the code below, we will insert an element at a specific position in the
list.
a = [1, 3]

# Insert 2 at index 1
[Link](1, 2)
print(a)

Output
[1, 2, 3]
pop():
Syntax: list_name.pop(index)
In the code below, we will remove the last element from the list.
a = [1, 2, 3]

# Remove and return the last element in the list


[Link]()
print(a)

Output
[1, 2]
remove():
Syntax: list_name.remove(element)
In the code below, we will remove the first occurrence of a specified
element from the list.
a = [1, 2, 3]

# Remove the first occurrence of 2


[Link](2)
print(a)

[Link] [Link]., [Link].,


Python programming

Output
[1, 3]
reverse():
Syntax: list_name.reverse()
In the code below, we will reverse the order of the elements in the list.
a = [1, 2, 3]

# Reverse the list order


[Link]()
print(a)

Output
[3, 2, 1]
sort():
Syntax: list_name.sort(key=None, reverse=False)
In the code below, we will sort the elements of the list in ascending
order
a = [3, 1, 2]

# Sort the list in ascending order


[Link]()
print(a)

Output
[1, 2, 3]
Tuples:
Python Tuples
A tuple in Python is an immutable ordered collection of elements.

[Link] [Link]., [Link].,


Python programming

 Tuples are similar to lists, but unlike lists, they cannot be changed
after their creation (i.e., they are immutable).
 Tuples can hold elements of different data types.
 The main characteristics of tuples are
being ordered , heterogeneous and immutable.
Creating a Tuple
A tuple is created by placing all the items inside parentheses (),
separated by commas. A tuple can have any number of items and they
can be of different data types.
Example:
tup = ()
print(tup)

# Using String
tup = ('Geeks', 'For')
print(tup)

# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))

# Using Built-in Function


tup = tuple('Geeks')
print(tup)

Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Let's understand tuple in detail:

[Link] [Link]., [Link].,


Python programming

Creating a Tuple with Mixed Datatypes.


Tuples can contain elements of various data types, including other
tuples, lists, dictionaries and even functions.
Example:
tup = (5, 'Welcome', 7, 'Geeks')
print(tup)

# Creating a Tuple with nested tuples


tup1 = (0, 1, 2, 3)
tup2 = ('python', 'geek')
tup3 = (tup1, tup2)
print(tup3)

# Creating a Tuple with repetition


tup1 = ('Geeks',) * 3
print(tup1)

# Creating a Tuple with the use of loop


tup = ('Geeks')
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)

Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)

[Link] [Link]., [Link].,


Python programming

(((('Geeks',),),),)
((((('Geeks',),),),),)
Python Tuple Basic Operations
Below are the Python tuple operations.
 Accessing of Python Tuples
 Concatenation of Tuples
 Slicing of Tuple
 Deleting a Tuple
Accessing of Tuples
We can access the elements of a tuple by using indexing and slicing,
similar to how we access elements in a list. Indexing starts at 0 for the
first element and goes up to n-1, where n is the number of elements in
the tuple. Negative indexing starts from -1 for the last element and goes
backward.
Example:
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])

# Accessing a range of elements using slicing


print(tup[1:4])
print(tup[:3])

# Tuple unpacking
tup = ("Geeks", "For", "Geeks")

# This line unpack values of Tuple1


a, b, c = tup
print(a)
print(b)
print(c)

Output

[Link] [Link]., [Link].,


Python programming

G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks
Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation
combines two or more tuples to create a new tuple.
Note: Only the same datatypes can be combined with concatenation, an
error arises if a list and a tuple are combined.

tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')

tup3 = tup1 + tup2


print(tup3)

Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Slicing of Tuple

[Link] [Link]., [Link].,


Python programming

Slicing a tuple means creating a new tuple from a subset of elements of


the original tuple. The slicing syntax is tuple[start:stop:step].
Note- Negative Increment values can also be used to reverse the
sequence of Tuples.

tup = tuple('GEEKSFORGEEKS')

# Removing First element


print(tup[1:])

# Reversing the Tuple


print(tup[::-1])

# Printing elements of a Range


print(tup[4:9])

Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')
Deleting a Tuple

[Link] [Link]., [Link].,


Python programming

Since tuples are immutable, we cannot delete individual elements of a


tuple. However, we can delete an entire tuple using del statement.
Note: Printing of Tuple after deletion results in an Error.
tup = (0, 1, 2, 3, 4)
del tup

print(tup)
Output
ERROR!
Traceback (most recent call last):
File "<[Link]>", line 6, in <module>
NameError: name 'tup' is not defined
Tuple Unpacking with Asterisk (*)
In Python, the " * " operator can be used in tuple unpacking to grab
multiple items into a list. This is useful when you want to extract just a
few specific elements and collect the rest together.
tup = (1, 2, 3, 4, 5)

a, *b, c = tup

print(a)
print(b)
print(c)

Output
1
[2, 3, 4]
5
Explanation:
 a gets the first item.
 c gets the last item.
 *b collects everything in between into a list.

[Link] [Link]., [Link].,


Python programming

Difference between lists and tuples:


In Python, lists and tuples both store collections of data, but differ in
mutability, performance and memory usage. Lists are mutable,
allowing modifications, while tuples are immutable. Choosing between
them depends on whether you need to modify the data or prioritize
performance and memory efficiency.
Key Differences between List and Tuple
[Link] List Tuple

Lists are mutable(can be Tuples are immutable(cannot


1
modified). be modified).

Iteration over lists is time-


2 Iterations over tuple is faster
consuming.

Lists are better for performing Tuples are more suitable for
3 operations, such as insertion accessing elements
and deletion. efficiently.

Tuples consumes less


4 Lists consume more memory.
memory

Lists have several built-in Tuples have fewer built-in


5
methods. methods.

[Link] [Link]., [Link].,


Python programming

[Link] List Tuple

Lists are more prone to


Tuples, being immutable are
6 unexpected changes and
less error prone.
errors.

Mutability Test: List vs Tuples


List are Mutable
Lists can be modified, meaning their elements can be changed, added
or removed after creation.
a = [1, 2, 4, 4, 3, 3, 3, 6, 5]

# Modifying an element in the list `a`


a[3] = 77
print(a)

Output
[1, 2, 4, 77, 3, 3, 3, 6, 5]
Explanation: Here, we modified the fourth element (index 3) from 4
to 77. Lists allow direct modification of their elements.
Tuples are Immutable
Tuples cannot be modified after creation. Any attempt to change an
element will result in an error.
b = (0, 1, 2, 3)

# Attempting to modify a tuple


b[0] = 4
print(b)

Hangup (SIGHUP)
Traceback (most recent call last):

[Link] [Link]., [Link].,


Python programming

File "/home/guest/sandbox/[Link]", line 4, in <module>


b[0] = 4
~^^^
TypeError: 'tuple' object does not support item assignment
Explanation: Tuples do not support item assignment, making them
immutable. This prevents unintended modifications.
Dictionaries:
Dictionaries in Python
Python dictionary is a data structure that stores the value in key:
value pairs. Values in a dictionary can be of any data type and can
be duplicated, whereas keys can't be repeated and must
be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries,
which makes it easier to find values.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
How to Create a Dictionary
Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a 'comma'.
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)

# create dictionary using dict() constructor


d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

[Link] [Link]., [Link].,


Python programming

{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}


 Dictionary keys are case sensitive: the same name but different
cases of Key will be treated distinctly.
 Keys must be immutable: This means keys can be strings, numbers
or tuples but not lists.
 Keys must be unique: Duplicate keys are not allowed and any
duplicate key will overwrite the previous value.
 Dictionary internally uses Hashing. Hence, operations like search,
insert, delete can be performed in Constant Time.
From Python 3.7 Version onward, Python dictionary are Ordered.
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square
brackets or get() method.
d = { "name": "Prajjwal", 1: "Python", (1, 2): [1,2,4] }

# Access using key


print(d["name"])

# Access using get()


print([Link]("name"))

Output
Prajjwal
Prajjwal
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using
assignment.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

# Adding a new key-value pair


d["age"] = 22

[Link] [Link]., [Link].,


Python programming

# Updating an existing value


d[1] = "Python dict"

print(d)

Output
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Removing Dictionary Items
We can remove items from dictionary using the following methods:
 del: Removes an item by key.
 pop(): Removes an item by key and returns its value.
 clear(): Empties the dictionary.
 popitem(): Removes and returns the last key-value pair.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}

# Using del to remove an item


del d["age"]
print(d)

# Using pop() to remove an item and return the value


val = [Link](1)
print(val)

# Using popitem to removes and returns


# the last key-value pair.
key, val = [Link]()
print(f"Key: {key}, Value: {val}")

# Clear all items from the dictionary


[Link]()
print(d)

Output

[Link] [Link]., [Link].,


Python programming

{1: 'Geeks', 2: 'For', 3: 'Geeks'}


Geeks
Key: 3, Value: Geeks
{}

Difference between List and Dictionary in Python

Lists and Dictionaries in Python are inbuilt data structures that are used
to store data. Lists are linear in nature whereas dictionaries stored the
data in key-value pairs. In this article, we will see the difference between
the two and find out the time complexities and space complexities which
arises when we try to store data and try to perform certain operations on
them.
Lists in Python
In Python, a list is a built-in dynamic sized array (automatically grows
and shrinks). We can store all types of items (including another list) in a
list. A list may contain mixed type of items, this is possible because a
list mainly stores references at contiguous locations and actual items
maybe stored at different locations.
Example: In this example, we will see how to create a simple one-
dimensional list as well as a two-dimensional list in Python and access
its values using the list index
# Python program to demonstrate Lists

# Creating a 1D List
a = ["Geeks", "For", "Geeks"] # List of Strings
print(a)

# Accessing particular elements


print(a[0])
print(a[0][1])
print(a[1])

[Link] [Link]., [Link].,


Python programming

# Creating a 2D List
a = [['Geeks', 'For'], ['Geeks']]
print(a)

# Accessing particular elements


print(a[0])
print(a[0][1])
print(a[1])

Output
List containing multiple values: ['Geeks', 'For', 'Geeks']
Geeks
e
For

Multi-Dimensional List: [['Geeks', 'For'], ['Geeks']]


['Geeks', 'For']
For
['Geeks']
Dictionary in Python
A Python dictionary is a data structure that stores the value in key: value
pairs. Values in a dictionary can be of any data type and can be
duplicated, whereas keys can’t be repeated and must be immutable.
Example: In this example, we will see how to create a simple dictionary
with similar key types as well as a dictionary with mixed key types.
# Creating a Dictionary with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("Dictionary with the use of Integer Keys: ", Dict)

[Link] [Link]., [Link].,


Python programming

# Accessing particular elements


print(Dict[1])
print(Dict[2])

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ", Dict)

# Accessing particular elements


print(Dict['Name'])
print(Dict[1])

Output
Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
For

Dictionary with the use of Mixed Keys: {'Name': 'Geeks', 1: [1, 2, 3, 4]}
Geeks
[1, 2, 3, 4]
Difference between a List and a Dictionary
The following table shows some differences between a list and a
dictionary in Python:

List Dictionary

The list is a collection of The dictionary is a hashed structure of


index value pairs like the key and value pairs.
ArrayList in Java and

[Link] [Link]., [Link].,


Python programming

List Dictionary

Vectors in C++.

The dictionary is created by placing


The list is created by placing
elements in { } as "key":"value", each
elements in [ ] separated by
key-value pair is separated by commas
commas ", "
", "

The indices of the list are The keys of the dictionary can be of
integers starting from 0. any immutable data type.

The elements are accessed


The elements are accessed via key.
via indices.

They are unordered in python 3.6 and


The order of the elements
below and are ordered in python 3.7
entered is maintained.
and above.

Lists can duplicate values Dictionaries cannot contain duplicate


since each values have keys but can contain duplicate values
unique index. since each value has unique key.

Average time taken to search Average time taken to search a key in


a value in list takes O[n]. dictionary takes O[1].

Average time to delete a


Average time to delete a certain key
certain value from a list takes
from a dictionary takes O[1].
O[n].

[Link] [Link]., [Link].,


Python programming

UNIT-V
Python File Handling: Types of files in Python - Opening and Closing
files-Reading and Writing files:write() and writelines() methods-
append() method – read() and readlines() methods – with keyword –
Splitting words – File methods - File PositionsRenaming and deleting
files.
Python File Handling:
[Link] File Open
1.1 Open a File on the Server
1.2 Read Only Parts of the File
1.3 Read Lines
1.4 Close Files
2. Python File Write
2.1 Write to an Existing File
2.2 Create a New File
3. Python Delete File
3.1 Delete a File
3.2 Delete Folder

[Link] [Link]., [Link].,


Python programming

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and


deleting files.

File Handling

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does
not exist
"a" - Append - Opens a file for appending, creates the file if it does not
exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text
mode

"t" - Text - Default value. Text mode


"b" - Binary - Binary mode (e.g. images)
Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("[Link]")

The code above is the same as:

[Link] [Link]., [Link].,


Python programming

f = open("[Link]", "rt")

Because "r" for read, and "t" for text are the default values, you do not
need to specify them.

Python File Open


Open a File on the Server:

Assume we have the following file, located in the same folder as Python:

[Link]
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for
reading the content of the file:

Example
f = open("[Link]", "r")
print([Link]())

If the file is located in a different location, you will have to specify the
file path, like this:

Example

Open a file on a different location:


f = open("D:\\myfiles\[Link]", "r")
print([Link]())
Read Only Parts of the File:

[Link] [Link]., [Link].,


Python programming

By default the read() method returns the whole text, but you can also
specify how many characters you want to return:

Example

Return the 5 first characters of the file:


f = open("[Link]", "r")
print([Link](5))
Read Lines:

You can return one line by using the readline() method:

Example

Read one line of the file:


f = open("[Link]", "r")
print([Link]())

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:


f = open("[Link]", "r")
print([Link]())
print([Link]())

By looping through the lines of the file, you can read the whole file, line
by line:

Example

Loop through the file line by line:

[Link] [Link]., [Link].,


Python programming

f = open("[Link]", "r")
for x in f:
print(x)
Close Files:

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finished with it:


f = open("[Link]", "r")
print([Link]())
[Link]()
Python File Write
Write to an Existing File:

To write to an existing file, you must add a parameter to


the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example

Open the file "[Link]" and append content to the file:


f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:

[Link] [Link]., [Link].,


Python programming

f = open("[Link]", "r")
print([Link]())
Example

Open the file "[Link]" and overwrite the content:


f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()

#open and read the file after the overwriting:


f = open("[Link]", "r")
print([Link]())

Note: the "w" method will overwrite the entire file.


Create a New File:

To create a new file in Python, use the open() method, with one of the
following parameters:

"x" - Create - will create a file, returns an error if the file exists

"a" - Append - will create a file if the specified file does not exists

"w" - Write - will create a file if the specified file does not exists

Example

Create a file called "[Link]":


f = open("[Link]", "x")

Result: a new empty file is created!

[Link] [Link]., [Link].,


Python programming

Example

Create a new file if it does not exist:


f = open("[Link]", "w")
Python Delete File
Delete a File:

To delete a file, you must import the OS module, and run


its [Link]() function:

Example

Remove the file "[Link]":


import os
[Link]("[Link]")
Check if File exist:

To avoid getting an error, you might want to check if the file exists
before you try to delete it:

Example

Check if file exists, then delete it:


import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")
Delete Folder:

To delete an entire folder, use the [Link]() method:

[Link] [Link]., [Link].,


Python programming

Example

Remove the folder "myfolder":


import os
[Link]("myfolder")

Note: You can only remove empty folders.


Reading and Writing to text files in Python
Last Updated : 02 Jan, 2025

Python provides built-in 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 called EOL (End of Line), which is the new line
character ('\n') in Python by default.
 Binary files: In this type of file, there is no terminator for a line, and
the data is stored after converting it into machine-understandable
binary language.
This article will focus on opening, closing, reading, and writing data in a
text file. Here, we will also see how to get Python output in a text file.
Table of Content
 Opening a Text File
 Read Text File
 Write to Text File
 Appending to a File
 Closing a Text File
Opening a Text File in Python
It is done using the open() function. No module is required to be
imported for this function.
File_object = open(r"File_Name","Access_Mode")

[Link] [Link]., [Link].,


Python programming

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


object for MyFile2.
# Open function to open the file "[Link]"
# (same directory) in append mode and
file1 = open("[Link]","a")

# store its reference in the variable file1


# and "[Link]" in D:\Text in file2
file2 = open(r"D:\Text\[Link]","w+")
Also Read: File Mode in Python
Python Read Text File
There are three ways to read txt file in Python:
 Using read()
 Using readline()
 Using readlines()
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.
File_object.read([n])
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.
File_object.readline([n])
Reading a File Using readlines()
readlines(): Reads all the lines and return them as each line a string
element in a list.
File_object.readlines()
Note: '\n' is treated as a special character of two bytes.
In this example, a file named "[Link]" is created and opened in write
mode ( "w" ). Data is written to the file
using write and writelines methods. The file is then reopened in read and
append mode ( "r+" ). Various read operations,
including read , readline , readlines , and the use of seek , demonstrate
different ways to retrieve data from the file. Finally, the file is closed.

[Link] [Link]., [Link].,


Python programming

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


L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

# \n is placed to indicate EOL (End of Line)


[Link]("Hello \n")
[Link](L)
[Link]() # to change file access modes

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

print("Output of Read function is ")


print([Link]())
print()

# seek(n) takes the file handle to the nth


# byte from the beginning.
[Link](0)

print("Output of Readline function is ")


print([Link]())
print()

[Link](0)

# To show difference between read and readline


print("Output of Read(9) function is ")
print([Link](9))
print()

[Link](0)

print("Output of Readline(9) function is ")


print([Link](9))

[Link](0)

[Link] [Link]., [Link].,


Python programming

# readlines function
print("Output of Readlines function is ")
print([Link]())
print()
[Link]()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['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()
Reference: write() VS writelines()
Writing to a Python Text File Using write()
write(): Inserts the string str1 in a single line in the text file.
File_object.write(str1)
file = open("[Link]", "w")

for i in range(3):
name = input("Enter the name of the employee: ")
[Link](name)
[Link]("\n")

[Link] [Link]., [Link].,


Python programming

[Link]()

print("Data is written into the file.")


Output:
Data is written into the file.
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.
File_object.writelines(L) for L = [str1, str2, str3]
file1 = open("[Link]", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
[Link](name + '\n')

[Link](lst)
[Link]()
print("Data is written into the file.")
Output:
Data is written into the file.
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.
file1 = open("[Link]", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
[Link](L)
[Link]()

# Append-adds at last
file1 = open("[Link]", "a") # append mode
[Link]("Today \n")

[Link] [Link]., [Link].,


Python programming

[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]())
print()
[Link]()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \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.
File_object.close()
# Opening and Closing a file "[Link]"
# for object name file1.
file1 = open("[Link]","a")
[Link]()

[Link] [Link]., [Link].,

You might also like