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

Python III (File

The document discusses abstraction and encapsulation in Python, highlighting their importance in object-oriented programming. Abstraction allows developers to hide complex implementation details using abstract classes and methods, while encapsulation restricts direct access to an object's data through public, protected, and private members. Additionally, it covers the implementation of lambda functions, which are anonymous functions that can take multiple arguments but return a single expression.

Uploaded by

Anshu Jayswal
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)
3 views43 pages

Python III (File

The document discusses abstraction and encapsulation in Python, highlighting their importance in object-oriented programming. Abstraction allows developers to hide complex implementation details using abstract classes and methods, while encapsulation restricts direct access to an object's data through public, protected, and private members. Additionally, it covers the implementation of lambda functions, which are anonymous functions that can take multiple arguments but return a single expression.

Uploaded by

Anshu Jayswal
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

Abstraction in Python

Abstraction is one of the core principles of object-oriented programming


(OOP) in Python. This way developers hide unnecessary implementation
details and expose only the relevant functionalities. For example, users
of Tpoint Tech may find the content easy to understand, but they are
unaware of the processes involved in gathering, organizing, and publishing
it.

In Python, data abstraction can be achieved with the help of the abstract
classes and methods from the abc module.

Importance of Abstraction in Python


Abstraction allows programmers to hide complex implementation details
while displaying the users only the essential data and functions. Data
abstraction helps making it easier in order to design modular as well as
properly structured code. It also helps simplifying the understanding and
maintenance of the program, promoting the reusability of code and
improving the developer collaboration.

Implementing Data Abstraction in Python


The abstraction is defined in the following two ways:

o Abstract classes
o Abstract Method

Abstract Class
An abstract class in Python is a class that comprises at least one abstract
method and is not directly instantiable. Abstract methods are classes without
a body that defines common behaviors for derived classes. An abstract
method cannot exist without its parent class.

To enforce abstract methods in a particular class, we first need to import


the ABC module from abc, inherit from ABC, and use the abstract decorator
for methods tagged as abstract.

Example
1. from abc import ABC, abstractmethod
2.
3. # Abstract class
4. class Vehicle(ABC):
5.
6. @abstractmethod
7. def start(self):
8. pass # Abstract method with no implementation
9.
10. @abstractmethod
11. def stop(self):
12. pass
13.
14. # Concrete class implementing the abstract methods
15. class Car(Vehicle):
16.
17. def start(self):
18. print("Car is starting with a key ignition.")
19.
20. def stop(self):
21. print("Car is stopping using the brake.")
22.
23. # Trying to instantiate an abstract class will raise an error
24. # vehicle = Vehicle() # TypeError
25.
26. # Creating an instance of the concrete class
27. my_car = Car()
28. my_car.start()
29. my_car.stop()
Output:

Car is starting with a key ignition.


Car is stopping using the brake.
Explanation:

Vehicle is an abstract class because it inherits ABC. The methods start() and
stop() are abstract. Any subclass is obligated to implement these methods.
The Car class actually implements these two methods. If one tries to create
an object of Vehicle directly, it will raise a TypeError.

Abstract Method
An abstract method in Python is a method declared in a base class, but lack
implementation. It serve as a placeholders that derived classes must
override. This method ensures a reliable interface across subclasses,
promising to provide their own implementation. We can define an abstract
method using the @abstractmethod decorator from the abc module.
Example
1. from abc import ABC, abstractmethod
2.
3. # Defining an abstract class
4. class Animal(ABC):
5.
6. @abstractmethod
7. def make_sound(self):
8. """Abstract method to be implemented by subclasses"""
9. pass
10.
11. # Concrete subclass implementing the abstract method
12. class Dog(Animal):
13.
14. def make_sound(self):
15. return "Bark!"
16.
17. # Concrete subclass implementing the abstract method
18. class Cat(Animal):
19.
20. def make_sound(self):
21. return "Meow!"
22.
23. # Trying to instantiate an abstract class will raise an error
24. # animal = Animal() # This will raise TypeError
25.
26. # Creating objects of concrete classes
27. dog = Dog()
28. cat = Cat()
29.
30. print(dog.make_sound())
31. print(cat.make_sound())
Output:

Bark!
Meow!
Explanation:

The make_sound() method on the Animal class lets it qualify as an abstract


class and, hence, must defined by subclasses. Dog and Cat classes are
inherited from Animal and return "Bark!" and "Meow!" for make_sound(),
respectively. Hence they override it. A TypeError can be raised when trying
to instantiate Animal directly.
Encapsulation in Python
In Python, Encapsulation is a fundamental concept of object-oriented
programming (OOP). It refers to class as collections of data (variables) and
methods that operate on that data.

Encapsulation restricts some components of an object from being accessed


directly, so that unintended interference and data corruption may be
prevented.

How does Encapsulation Work in Python?


Encapsulation is implemented in Python by stopping users from directly
accessing certain parts of an object, while giving them the ability to access
those areas through other means (methods).

Access can be controlled using different access modifiers:

o Public Attribute: Accessible from anywhere.


o Protected Attributes (_singleUnderscore): Not intended for public
use, but still accessible.
o Private Attributes (__doubleUnderscore): Not directly accessible
from outside the class.

Member Syntax Accessible Accessible in Accessible


Type Inside Subclasses Outside Class
Class

Public [Link] Yes Yes Yes

Protecte self._va Yes Yes Yes (Not


d r (Recommended recommended)
inside subclasses
only)

Private self.__v Yes No (Unless using No (Direct


ar name mangling) access
restricted)

Implementation of Encapsulation in Python


Python uses three levels of access control for class members:

o public,
o protected, and
o private.
Let's explore each with examples.

Public Members
Public members can be accessed everywhere, inside the class, outside the
class, and inside derived (child) classes.

o Usage: No underscore before the variable name.

Example
1. class Car:
2. def __init__(self, brand, model):
3. [Link] = brand # Public attribute
4. [Link] = model # Public attribute
5.
6. def display(self):
7. print(f"Car: {[Link]} {[Link]}")
8.
9. # Creating an object
10. car = Car("Toyota", "Corolla")
11.
12. # Accessing public members
13. print([Link])
14. print([Link])
15.
16. # Calling public method
17. [Link]()
Output:

Toyota
Corolla
Car: Toyota Corolla
Explanation:

Public attributes (brand, model) will also be accessible outside the class. The
display() method which is also public can be accessed from other classes.

Protected Members
Protected members are indicated by a single underscore (_variable).

o Usage: It can be accessed outside the class but should only be


accessed within the class and subclasses (not enforced, just a
convention).

Example
1. class Car:
2. def __init__(self, brand, model, engine):
3. [Link] = brand # Public attribute
4. self._model = model # Protected attribute
5. self._engine = engine # Protected attribute
6.
7. def _show_details(self): # Protected method
8. print(f"Brand: {[Link]}, Model: {self._model}, Engine: {self._engine
}")
9.
10. class ElectricCar(Car):
11. def __init__(self, brand, model, battery_capacity):
12. super().__init__(brand, model, "Electric")
13. self.battery_capacity = battery_capacity
14.
15. def show_info(self):
16. self._show_details() # Accessing protected method from subclas
s
17. print(f"Battery: {self.battery_capacity} kWh")
18.
19. # Creating an object of ElectricCar
20. tesla = ElectricCar("Tesla", "Model S", 100)
21.
22. # Accessing protected members from subclass
23. tesla.show_info()
24.
25. # Accessing protected members outside the class (not recommended
)
26. print(tesla._model) # Works, but not recommended
Output:

Brand: Tesla, Model: Model S, Engine: Electric


Battery: 100 kWh
Model S
Explanation:

_model and _engine are protected attributes,_show_details() is


a protected method. They can be accessed in subclasses, but it's not
recommended to use them directly outside the class.

Private Members
Private members are indicated by double underscores (__variable).

o Usage: They cannot be accessed directly outside the class.

Example
1. class BankAccount:
2. def __init__(self, account_number, balance):
3. self.account_number = account_number # Public attribute
4. self.__balance = balance # Private attribute
5.
6. def get_balance(self): # Getter method
7. return self.__balance
8.
9. def set_balance(self, amount): # Setter method
10. if amount >= 0:
11. self.__balance = amount
12. else:
13. print("Invalid amount! Balance cannot be negative.")
14.
15. # Creating an account object
16. account = BankAccount("123456789", 1000)
17.
18. # Accessing public member
19. print(account.account_number) # Works fine
20.
21. # Trying to access private member directly (will raise AttributeError)
22. # print(account.__balance) # Uncommenting this will cause an error
23.
24. # Using getter method to access private attribute
25. print(account.get_balance()) # Works fine
26.
27. # Using setter method to update private attribute
28. account.set_balance(2000)
29. print(account.get_balance()) # Updated balance
30.
31. # Accessing private attribute using name mangling (Not recommend
ed)
32. print(account._BankAccount__balance) # Works, but should be avoid
ed
Output:

123456789
1000
2000
2000
Explanation:

__balance is a private attribute; direct access is not allowed. We


use getter (get_balance()) and setter (set_balance()) methods to control
access. Python renames __balance internally as _BankAccount__balance,
allowing access via name mangling (but this is bad practice).

Conclusion
Encapsulation hides the internal details and the implementation of the
object's attributes by preventing direct access. In Python, encapsulation is
applied through public, protected, and private members for class attributes,
and controlling access through getters and setters. It improves the security,
maintainability and structure of the code because of the convention-based
approach in Python.

Encapsulation in Python FAQs


1. What is Encapsulation in Python?

Encapsulation is an object oriented programming principle that forbids


unrestricted access to an object's data and methods. Access is provided
through controlled interfaces called public methods which ensures that the
data is secure and protected.

2. How is Encapsulation Implemented in Python?

Encapsulation is implemented using access specifiers:


o Self Variable ([Link]): Public Members can be accessed from
anywhere. Protected Members are denoted by a single underscore
(_var), meaning it is available for internal use.
o Double underscore(__var): It is called Private Members, meaning
that there is no direct access to it.
3. Why is Encapsulation Important?

Encapsulation Provides:

o Intended modification is prevented so data is secured.


o Defined methods are the only way data can be accessed meaning
method controlled access is provided.
o Structure and Modularity improves so the code becomes maintainable.
4. How Do Getters and Setters Work in Encapsulation?

Private variables can be accessed with the help of setter and getter
methods, respectively.

Example
1. class BankAccount:
2. def __init__(self, balance):
3. self.__balance = balance
4.
5. def get_balance(self): # Getter
6. return self.__balance
7.
8. def set_balance(self, amount): # Setter
9. if amount >= 0:
10. self.__balance = amount
11. else:
12. print("Invalid amount!")
13.
14. account = BankAccount(1000)
15. print(account.get_balance())
16. account.set_balance(2000)
17. print(account.get_balance())
Output:

1000
2000
5. Can Private Members Be Accessed Outside the Class in Python?
Direct access is restricted making it impossible to avail the class attribute.
However, we can access Private Variable through name mangling.
(_ClassName__privateVar).

Next

Python Lambda Functions


This tutorial will study anonymous, commonly called lambda functions in
Python. A lambda function can take n number of arguments at a time. But it
returns only one argument at a time. We will understand what they are, how
to execute them, and their syntax.

What are Lambda Functions in Python?


Lambda Functions in Python are anonymous functions, implying they don't
have a name. The def keyword is needed to create a typical function in
Python, as we already know. We can also use the lambda keyword in Python
to define an unnamed function.

Syntax
The syntax of the Lambda Function is given below -

1. lambda arguments: expression


This function accepts any count of inputs but only evaluates and returns one
expression. That means it takes many inputs but returns only one output.

Lambda functions can be used whenever function arguments are necessary.


In addition to other forms of formulations in functions, it has a variety of
applications in certain coding domains. It's important to remember that
according to syntax, lambda functions are limited to a single statement.

Example
Here we share some examples of lambda functions in Python for learning
purposes. Program Code 1:

Now we gave an example of a lambda function that adds 4 to the input


number is shown below.
1. # Code to demonstrate how we can use a lambda function for adding 4 nu
mbers
2. add = lambda num: num + 4
3. print( add(6) )
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

10
Here we explain the above code. The lambda function is "lambda num:
num+4" in the given programme. The parameter is num, and the computed
and returned equation is num * 4.

There is no label for this function. It generates a function object associated


with the "add" identifier. We can now refer to it as a standard function. The
lambda statement, "lambda num: num+4", is written using the add function,
and the code is given below: Program Code 2:

Now we gave an example of a lambda function that adds 4 to the input


number using the add function. The code is shown below -

1. def add( num ):


2. return num + 4
3. print( add(6) )
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

10
Program Code 3:

Now we gave an example of a lambda function that multiply 2 numbers and


return one result. The code is shown below -

1. a = lambda x, y : (x * y)
2. print(a(4, 5))
Output:

Now we compile the above code in python, and after successful compilation,
we run it. Then the output is given below -

20
Program Code 4:
Now we gave another example of a lambda function that adds 2 numbers
and return one result. The code is shown below -

1. a = lambda x, y, z : (x + y + z)
2. print(a(4, 5, 5))
Output:

Now we compile the above code in python, and after successful compilation,
we run it. Then the output is given below -

14

What's the Distinction Between Lambda and


Def Functions?
Let's glance at this instance to see how a conventional def defined function
differs from a function defined using the lambda keyword. This program
calculates the reciprocal of a given number:

Program Code:

1. # Python code to show the reciprocal of the given number to highlight the
difference between def() and lambda().
2. def reciprocal( num ):
3. return 1 / num
4.
5. lambda_reciprocal = lambda num: 1 / num
6.
7. # using the function defined by def keyword
8. print( "Def keyword: ", reciprocal(6) )
9.
10. # using the function defined by lambda keyword
11. print( "Lambda keyword: ", lambda_reciprocal(6) )
Output:

Now we compile the above code in python, and after successful compilation,
we run it. Then the output is given below -

Def keyword: 0.16666666666666666


Lambda keyword: 0.16666666666666666
Explanation:
The reciprocal() and lambda_reciprocal() functions act similarly and as
expected in the preceding scenario. Let's take a closer look at the sample
above:

Both of these yield the reciprocal of a given number without employing


Lambda. However, we wanted to declare a function with the name reciprocal
and send a number to it while executing def. We were also required to use
the return keyword to provide the output from wherever the function was
invoked after being executed.

Using Lambda: Instead of a "return" statement, Lambda definitions always


include a statement given at output. The beauty of lambda functions is their
convenience. We need not allocate a lambda expression to a variable
because we can put it at any place a function is requested.

Python File Handling


17 Apr 2025 | 23 min read

Introduction:
In this tutorial, we are discussing Python file handling. Python supports the
file-handling process. Till now, we were taking the input from the console and
writing it back to the console to interact with the user. Users can easily
handle the files, like read and write the files in Python. In another
programming language, the file-handling process is lengthy and complicated.
But we know Python is an easy programming language. So, like other things,
file handling is also effortless and short in Python.

Sometimes, it is not enough to only display the data on the console. The data
to be displayed may be very large, and only a limited amount of data can be
displayed on the console since the memory is volatile, it is impossible to
recover the programmatically generated data again and again.

The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) after the
program termination.

In Python, files are treated in two modes as text or binary. The file may be in
the text or binary format, and each line of a file is ended with the special
character like a comma (,) or a newline character. Python executes the code
line by line. So, it works in one line and then asks the interpreter to start the
new line again. This is a continuous process in Python.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Opening a file
A file operation starts with the file opening. At first, open the File then Python
will start the operation. File opening is done with the open() function in
Python. This function will accepts two arguments, file name and access mode
in which the file is accessed. When we use the open() function, that time we
must be specified the mode for which the File is opening. The function
returns a file object which can be used to perform various operations like
reading, writing, etc.

Syntax:

The syntax for opening a file in Python is given below -

1. file object = open(<file-name>, <access-mode>, <buffering>)


The files can be accessed using various modes like read, write, or append.
The following are the details about the access mode to open a file.

SN Access mode Description

1 r r means to read. So, it


opens a file for read-only
operation. The file pointer
exists at the beginning.
The file is by default open
in this mode if no access
mode is passed.

2 rb It opens the file to read-


only in binary format. The
file pointer exists at the
beginning of the file.

3 r+ It opens the file to read


and write both. The file
pointer exists at the
beginning of the file.

4 rb+ It opens the file to read


and write both in binary
format. The file pointer
exists at the beginning of
the file.

5 w It opens the file to write


only. It overwrites the file if
previously exists or creates
a new one if no file exists
with the same name. The
file pointer exists at the
beginning of the file.

6 wb It opens the file to write


only in binary format. It
overwrites the file if it
exists previously or creates
a new one if no file exists.
The file pointer exists at
the beginning of the file.
7 w+ It opens the file to write
and read both. It is
different from r+ in the
sense that it overwrites the
previous file if one exists
whereas r+ doesn't
overwrite the previously
written file. It creates a
new file if no file exists.
The file pointer exists at
the beginning of the file.

8 wb+ It opens the file to write


and read both in binary
format. The file pointer
exists at the beginning of
the file.

9 a It opens the file in the


append mode. The file
pointer exists at the end of
the previously written file if
exists any. It creates a new
file if no file exists with the
same name.

10 ab It opens the file in the


append mode in binary
format. The pointer exists
at the end of the
previously written file. It
creates a new file in binary
format if no file exists with
the same name.

11 a+ It opens a file to append


and read both. The file
pointer remains at the end
of the file if a file exists. It
creates a new file if no file
exists with the same name.

12 ab+ It opens a file to append


and read both in binary
format. The file pointer
remains at the end of the
file.

Let's look at the simple example to open a file named "[Link]" (stored in the
same directory) in read mode and printing its content on the console.

Program code for read mode:

It is a read operation in Python. We open an existing file with the given code
and then read it. The code is given below -

1. #opens the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. if fileptr:
5. print("file is opened successfully")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

<class '_io.TextIOWrapper'>
file is opened successfully
In the above code, we have passed filename as a first argument and
opened file in read mode as we mentioned r as the second argument.
The fileptr holds the file object and if the file is opened successfully, it will
execute the print statement

Program code for Write Mode:

It is a write operation in Python. We open an existing file using the given


code and then write on it. The code is given below -

1. file = open('[Link]','w')
2. [Link]("Here we write a command")
3. [Link]("Hello users of JAVATPOINT")
4. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

1. > Hi
2. ERROR!
3. Traceback (most recent call last):
4. File "<stdin>", line 1, in <module>
5. NameError: name 'Hi' is not defined

The close() Method


The close method used to terminate the program. Once all the operations
are done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object.

We can perform any operation on the file externally using the file system
which is the currently opened in Python; hence it is good practice to close
the file once all the operations are done. Earlier use of the close() method
can cause the of destroyed some information that you want to write in your
File.

The syntax to use the close() method is given below.

Syntax

The syntax for closing a file in Python is given below -

1. [Link]()
Consider the following example.

Program code for Closing Method:

Here we write the program code for the closing method in Python. The code
is given below -

1. # opens the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. if fileptr:
5. print("The existing file is opened successfully in Python")
6.
7. #closes the opened file
8. [Link]()
After closing the file, we cannot perform any operation in the file. The file
needs to be properly closed. If any exception occurs while performing some
operations in the file then the program terminates without closing the file.

We should use the following method to overcome such type of problem.

1. try:
2. fileptr = open("[Link]")
3. # perform file operations
4. finally:
5. [Link]()

The with statement


The with statement was introduced in python 2.5. The with statement is
useful in the case of manipulating the files. It is used in the scenario where a
pair of statements is to be executed with a block of code in between.

Syntax:

The syntax of with statement of a file in Python is given below -

1. with open(<file name>, <access mode>) as <file-pointer>:


2. #statement suite
The advantage of using with statement is that it provides the guarantee to
close the file regardless of how the nested block exits.

It is always suggestible to use the with statement in the case of files


because, if the break, return, or exception occurs in the nested block of code
then it automatically closes the file, we don't need to write
the close() function. It doesn't let the file to corrupt.

Program code 1 for with statement:

Here we write the program code for with statement in Python. The code is
given below -

1. with open("[Link]",'r') as f:
2. content = [Link]();
3. print(content)
Program code 2 for with statement:
Here we write the program code for with statement in Python. The code is
given below -

1. with open("[Link]", "H") as f:


2. A = [Link]("Hello Coders")
3. Print(A)

Writing the file


To write some text to a file, we need to open the file using the open method
and then we can use the write method for writing in this File. If we want to
open a file that does not exist in our system, it creates a new one. On the
other hand, if the File exists, then erase the past content and add new
content to this File. the It is done by the following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.

a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.

Program code 1 for Write Method:

Here we write the program code for write method in Python. The code is
given below -

1. # open the [Link] in append mode. Create a new file if no such file exists.

2. fileptr = open("[Link]", "w")


3.
4. # appending the content to the file
5. [Link](''''''''Python is the modern programming language. It is done any
kind of program in shortest way.''')
6.
7. # closing the opened the file
8. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

[Link]
Python is the modern programming language. It is done any kind of program
in shortest way.
We have opened the file in w mode. The [Link] file doesn't exist, it created
a new file and we have written the content in the file using the write()
function

Program code 2 for Write Method:

Here we write the program code for write method in Python. The code is
given below -

1. with open([Link]', 'w') as file2:


2. [Link]('Hello coders')
3. [Link]('Welcome to javaTpoint')
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Hello coders
Welcome to javaTpoint
Program code 3 for Write Method:

Here we write the program code for write method in Python. The code is
given below -

1. #open the [Link] in write mode.


2. fileptr = open("[Link]","a")
3.
4. #overwriting the content of the file
5. [Link](" Python has an easy syntax and user-friendly interaction.")
6.
7. #closing the opened file
8. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern day language. It makes things so simple.


It is the fastest growing language Python has an easy syntax and user-
friendly interaction.
Snapshot of the [Link]
We can see that the content of the file is modified. We have opened the file
in a mode and it appended the content in the existing [Link].

To read a file using the Python script, the Python provides


the read() method. The read() method reads a string from the file. It can
read the data in the text as well as a binary format.

Syntax:

The syntax of read() method of a file in Python is given below -

1. [Link](<count>)
Here, the count is the number of bytes to be read from the file starting from
the beginning of the file. If the count is not specified, then it may read the
content of the file until the end.

Program code for read() Method:

Here we write the program code for read() method in Python. The code is
given below -

1. #open the [Link] in read mode. causes error if no such file exists.
2. fileptr = open("[Link]","r")
3. #stores all the data of the file into the variable content
4. content = [Link](10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
10. [Link]()
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

<class 'str'>
Python is
In the above code, we have read the content of [Link] by using
the read() function. We have passed count value as ten which means it will
read the first ten characters from the file.

If we use the following line, then it will print all content of the file. So, it only
prints 'Python is'. For read the whole file contents, the code is given below -

1. content = [Link]()
2. print(content)
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern-day language. It makes things so simple.


It is the fastest-growing programming language Python has easy an syntax
and user-friendly interaction.

Read file through for loop


We can use read() method when we open the file. Read method is also done
through the for loop. We can read the file using for loop. Consider the
following example.

Program code 1 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below
-

1. #open the [Link] in read mode. causes an error if no such file exists.
2. fileptr = open("[Link]","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern day language.


It makes things so simple.

Python has easy syntax and user-friendly interaction.


Program code 2 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below
-

1. A = ["Hello\n", "Coders\n", "JavaTpoint\n"]


2. f1 = open('[Link]', 'w')
3. [Link](A)
4. [Link]()
5. f1 = open('[Link]', 'r')
6. Lines = [Link]()
7. count = 0
8. for line in Lines:
9. count += 1
10. print("Line{}: {}".format(count, [Link]()))
Output:

Line1: H
Line2: e
Line3: l
Line4: l
Line5: o
Line6:
Line7: C
Line8: o
Line9: d
Line10: e
Line11: r
Line12: s
Line13:
Line14: J
Line15: a
Line16: v
Line17: a
Line18: T
Line19: p
Line20: o
Line21: i
Line22: n
Line23: t
Line24:

Read Lines of the file


Python facilitates to read the file line by line by using a
function readline() method. The readline() method reads the lines of the
file from the beginning, i.e., if we use the readline() method two times, then
we can get the first two lines of the file.

Consider the following example which contains a function readline() that


reads the first line of our file "[Link]" containing three lines. Consider the
following example.

Here we give the example of reading the lines using the readline() function in
Python. The code is given below -

1. #open the [Link] in read mode. causes error if no such file exists.
2. fileptr = open("[Link]","r");
3. #stores all the data of the file into the variable content
4. content = [Link]()
5. content1 = [Link]()
6. #prints the content of the file
7. print(content)
8. print(content1)
9. #closes the opened file
10. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern day language.

It makes things so simple.


We called the readline() function two times that's why it read two lines from
the [Link] means, if you called readline() function n times in your program,
then it read n number of lines from the file. This is the uses of readline()
function in Python. Python provides also the readlines() method which is
used for the reading lines. It returns the list of the lines till the end
of file(EOF) is reached.

Example 2:
Here we give the example of reading the lines using the readline() function in
Python. The code is given below -

1. #open the [Link] in read mode. causes error if no such file exists.
2. fileptr = open("[Link]","r");
3.
4. #stores all the data of the file into the variable content
5. content = [Link]()
6.
7. #prints the content of the file
8. print(content)
9.
10. #closes the opened file
11. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

['Python is the modern day language.\n', 'It makes things so simple.\n',


'Python has easy syntax and user-friendly interaction.']
Example 3:

Here we give the example of reading the lines using the readline() function in
Python. The code is given below -

1. A = ["Hello\n", "Coders\n", "JavaTpoint\n"]


2. f1 = open('[Link]', 'w')
3. [Link](A)
4. [Link]()
5. f1 = open('[Link]', 'r')
6. Lines = [Link]()
7. count = 0
8. for line in Lines:
9. count += 1
10. print("Line{}: {}".format(count, [Link]()))
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Line1: Hello
Line2: Coders
Line3: JavaTpoint

Creating a new file


The new file can be created by using one of the following access modes with
the function open().The open() function used so many parameters. The
syntax of it is given below -
file = open(path_to_file, mode)

x, a and w is the modes of open() function. The uses of these modes are
given below -

x: it creates a new file with the specified name. It causes an error a file
exists with the same name.

a: It creates a new file with the specified name if no such file exists. It
appends the content to the file if the file already exists with the specified
name.

w: It creates a new file with the specified name if no such file exists. It
overwrites the existing file.

Consider the following example.

Program code1 for Creating a new file:

Here we give an example for creating a new file in Python. For creates a file,
we have to used the open() method. The code is given below -

1. #open the [Link] in read mode. causes error if no such file exists.
2. fileptr = open("[Link]","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

<_io.TextIOWrapper name='[Link]' mode='x' encoding='cp1252'>


File created successfully
Program code2 for creating a new file:

Here we give an example for creating a new file in Python. For creates a file,
we have to use the open() method. Here we use try block for erase the
errors. The code is given below -

1. try:
2. with open('[Link]', 'w') as f:
3. [Link]('Here we create a new file')
4. except FileNotFoundError:
5. print("The file is does not exist")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The file is does not exist

File Pointer positions


Python provides the tell() method which is used to print the byte number at
which the file pointer currently exists. The tell() methods is return the
position of read or write pointer in this file. The syntax of tell() method is
given below -

1. [Link]()
Program code1 for File Pointer Position:

Here we give an example for how to find file pointer position in Python. Here
we use tell() method and it is return byte number. The code is given below -

1. # open the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",[Link]())
6.
7. #reading the content of the file
8. content = [Link]();
9.
10. #after the read operation file pointer modifies. tell() returns the locat
ion of the fileptr.
11.
12. print("After reading, the filepointer is at:",[Link]())
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 117
Program code2 for File Pointer Position:
Here we give another example for how to find file pointer position in Python.
Here we also use tell() method, which is return byte number. The code is
given below -

1. file = open("[Link]", "r")


2. print("The pointer position is: ", [Link]())
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The pointer position is: 0

Modifying file pointer position


In real-world applications, sometimes we need to change the file pointer
location externally since we may need to read or write the content at various
locations.

For this purpose, the Python provides us the seek() method which enables us
to modify the file pointer position externally. That means, using seek()
method we can easily change the cursor in the file, from where we want to
read or write a file.

Syntax:

The syntax for seek() method is given below -

1. <file-ptr>.seek(offset[, from)
The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as the
reference position. If it is set to 2, the end of the file pointer is used as the
reference position.

Consider the following example.

Here we give the example of how to modifying the pointer position using
seek() method in Python. The code is given below -

1. # open the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",[Link]())
6.
7. #changing the file pointer location to 10.
8. [Link](10);
9.
10. #tell() returns the location of the fileptr.
11. print("After reading, the filepointer is at:",[Link]())
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 10

Python OS module:
Renaming the file
The Python os module enables interaction with the operating system. It
comes from the Python standard utility module. The os module provides a
portable way to use the operating system-dependent functionality in Python.
The os module provides the functions that are involved in file processing
operations like renaming, deleting, etc. It provides us the rename() method
to rename the specified file to a new name. Using the rename() method, we
can easily rename the existing File. This method has not any return value.
The syntax to use the rename() method is given below.

Syntax:

The syntax of rename method in Python is given below -

1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the
modified name. We can change the file name bypassing these two
arguments.

Program code 1 for rename() Method:


Here we give an example of the renaming of the files using rename() method
in Python. The current file name is [Link], and the new file name is [Link].
The code is given below -

1. import os
2.
3. #rename [Link] to [Link]
4. [Link]("[Link]","[Link]")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The above code renamed current [Link] to [Link]


Program code 2 for rename() Method:

Here we give an example of the renaming of the files using rename() method
in Python. The current file name is the source, and the new file name is the
destination. The code is given below -

1. import os
2. def main():
3. i=0
4. path="D:/JavaTpoint/"
5. for filename in [Link](path):
6. destination = "new" + str(i) + ".png"
7. source = path + filename
8. destination = path + destination
9. [Link](source, destination)
10. i += 1
11.
12. if __name__ == '__main__':
13. main()

Removing the file


The os module provides the remove() method which is used to remove the
specified file.

Syntax:

The syntax of remove method is given below -

1. remove(file-name)
Program code 1 for remove() method:

1. import os;
2. #deleting the file named [Link]
3. [Link]("[Link]")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The file named [Link] is deleted.


Program code 2 for remove() Method:

Here we give an example of removing a file using the remove() method in


Python. The file name is [Link], which the remove() method deletes. Print
the command "This file is not existed" if the File does not exist. The code is
given below -

1. import os
2. if [Link]("[Link] "):
3. [Link]("[Link] ")
4. else:
5. print("This file is not existed")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

This file is not existed

Creating the new directory


The mkdir() method is used to create the directories in the current working
[Link] creates dictionary in numeric mode. If the file already presents in
the system, then it occurs error, which is known as FileExistsError in Python.
The mkdir() method does not return any kind of value. The syntax to create
the new directory is given below.

Syntax:

The syntax of mkdir() method in Python is given below -

1. [Link] (path, mode = 0o777, *, dir_fd = None)


Output:
Parameter:

The syntax of mkdir() method in Python is given below -

path - A path like object represent a path either bytes or the strings object.

mode - Mode is represented by integer value, which means mode is created.


If mode is not created then the default value will be 0o777. Its use is optional
in mkdir() method.

dir_fd - When the specified path is absolute, in that case dir_fd is ignored. Its
use is optional in mkdir() method.

Program code 1 for mkdir() Method:

Here we give the example of mkdir() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2.
3. #creating a new directory with the name new
4. [Link]("new")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Create a new dictionary which is named new


Program code 2 for mkdir() Method:

Here we give the example of mkdir() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2. path = '/D:/JavaTpoint'
3. try:
4. [Link](path)
5. except OSError as error:
6. print(error)
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

[Error 20] File exists: '/D:/JavaTpoint'


The getcwd() method:
This method returns the current working directory which have absolute
value. The getcwd() method returns the string value which represents the
working dictionary in Python. In getcwd() method, do not require any
parameter.

The syntax to use the getcwd() method is given below.

Syntax

The syntax of getcwd() method in Python is given below -

1. [Link]()
Program code 1 for getcwd() Method:

Here we give the example of getcwd() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

'C:\\Users\\DEVANSH SHARMA'
Program code 2 for getcwd() Method:

Here we give the example of getcwd() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2. c = [Link]()
3. print("The working directory is:", c)
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The working directory is: C:\\Users\\JavaTpoint

Changing the current working directory


The chdir() method is used to change the current working directory to a
specified [Link] chdir() method takes a single argument for the new
dictionary path. The chdir() method does not return any kind of value.

Syntax

The syntax of chdir() method is given below -

1. chdir("new-directory")
Program code 1 for chdir() Method:

Here we give the example of chdir() method by which we can change the
current working dictionary into new dictionary in Python. The code is given
below -

1. import os
2. # Changing current directory with the new directiory
3. [Link]("C:\\Users\\DEVANSH SHARMA\\Documents")
4. #It will display the current working directory
5. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

'C:\\Users\\DEVANSH SHARMA\\Documents'
Program code 2 for chdir() Method:

Here we give another example of chdir() method by which we can change


the current working dictionary into new dictionary in Python. The code is
given below -

1. import os
2. [Link](r"C:\Users\JavaTpoint")
3. print("Currently working directory is changed")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Currently working directory is changed

Deleting directory:
The rmdir() method is used to delete the specified directory. If the directory
is not empty then there is occurs OSError. The rmdir() method does not have
and kind of return value.

Syntax

1. [Link](directory name)
Program code 1 for rmdir() Method:

Here we give the example of rmdir() method by which we can delete a


dictionary in Python. The code is given below -

1. import os
2. #removing the new directory
3. [Link]("directory_name")
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

It will remove the specified directory.


Program code 2 for rmdir() Method:

Here we give another example of rmdir() method by which we can delete a


dictionary in Python. The code is given below -

1. import os
2. directory = "JavaTpoint"
3. parent = "/D:/User/Documents"
4. path = [Link](parent, directory)
5. [Link](path)
6. print("The directory '%s' is successfully removed", %directory)
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The directory 'JavaTpoint' is successfully removed


Output:

Here we give the example of rmdir() method by which we can delete a


dictionary in Python. Here we use try block for handle the error. The code is
given below -
1. import os
2. dir = "JavaTpoint"
3. parent = "/D:/User/Documents"
4. path = [Link](parent, dir)
5. try:
6. [Link](path)
7. print("The directory '%s' is successfully removed", %dir)
8. except OSError as error:
9. print(error)
10. print("The directory '%s' cannot be removed successfully", %dir)
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

[Error 30] Permission denied: '/D:/User/Documents/JavaTpoint'


The directory 'JavaTpoint' cannot be removed successfully

Writing Python output to the files:


In Python, there are the requirements to write the output of a Python script
to a file.

The check_call() method of module subprocess is used to execute a


Python script and write the output of that script to a file.

The following example contains two python scripts. The script [Link]
executes the script [Link] and writes its output to the text file [Link].

Program code:

[Link]

1. temperatures=[10,-20,-289,100]
2. def c_to_f(c):
3. if c< -273.15:
4. return "That temperature doesn't make sense!"
5. else:
6. f=c*9/5+32
7. return f
8. for t in temperatures:
9. print(c_to_f(t))
[Link]

1. import subprocess
2.
3. with open("[Link]", "wb") as f:
4. subprocess.check_call(["python", "[Link]"], stdout=f)

File Related Methods:


The file object provides the following methods to manipulate the files on
various operating systems. Here we discuss the method and their uses in
Python.

S Method Description
N

1 [Link]() It closes the opened file. The file once closed,


it can't be read or write anymore.

2 [Link]() It flushes the internal buffer.

3 [Link]() It returns the file descriptor used by the


underlying implementation to request I/O from
the OS.

4 [Link]() It returns true if the file is connected to a TTY


device, otherwise returns false.

5 [Link]() It returns the next line from the file.

6 [Link]([size]) It reads the file for the specified size.

7 [Link]([size]) It reads one line from the file and places the
file pointer to the beginning of the new line.

8 [Link]([sizeh It returns a list containing all the lines of the


int]) file. It reads the file until the EOF occurs using
readline() function.

9 [Link](offset[,fro It modifies the position of the file pointer to a


m) specified offset with the specified reference.

10 [Link]() It returns the current position of the file


pointer within the file.

11 [Link]([size]) It truncates the file to the optional specified


size.

12 [Link](str) It writes the specified string to a file

13 [Link](seq) It writes a sequence of the strings to a file.

Python Read CSV File


12 Jun 2025 | 5 min read
A CSV (Comma Separated Values) file is a form of plain text document
used to organize tabular information in a particular format. CSV file format is
a bounded text document that uses a comma in order to distinguish the
values.

The rows in the CSV document are the data log where each log is composed
of one or more fields, divided by commas. CSV is one of the popular file
formats used for importing and exporting the spreadsheets and databases.

In Python, we can read CSV files using the functions of built-in csv
module and the pandas library. In the following sections, we will explore
the different ways to read CSV files in Python.

To understand these approaches, we will be using the following CSV file.

File: [Link]

1. Organization,Industry,Employees
2. Google,IT,1500
3. Microsoft,IT,1300
4. Tata,Manufacturing,1000
5. Tpoint Tech,Education,200
6. Apple,IT,1200
In the above CSV file, we have some values separated by commas ','. We will
be using this file for the examples in the following sections.

Reading CSV Files in Python


There are different ways to read a CSV file in Python that use either the CSV
module or the pandas library.

o csv Module: The csv module is one of the built-in modules in Python.
It offers various classes and functions that help us read and write
tabular information in CSV file format.
To use csv module in Python, we need to import it. The following syntax will
guide us how to use the csv module for our purpose.

Syntax:

1. import csv

o pandas Library: The pandas library is an open-source Python library


used for data analysis and manipulation. It is one of the most essential
tool in Python that allows data scientists, analysts, and developers to
work with structured data.
Similar to the csv module, in order to work with pandas, we need to import it
first. Here is a syntax to import the pandas library into the Python programs.

Syntax:

1. import pandas

Ways to Read CSV Files in Python


We will now look at different ways possible for us to read CSV files in Python.

1) Using [Link]()
[Link]() is a function provided by the built-in csv module in Python. It is
used to read data from a CSV file. It returns a reader object, which can be
utilized in order to iterate over lines in the given CSV file.
Let us see an example of the [Link]() function.

Example
1. import csv
2.
3. # opening the CSV file
4. with open('[Link]', newline='') as file:
5. # using the reader() function to read the content of the file
6. reader = [Link](file)
7.
8. # printing each row of the table
9. for row in reader:
10. print(row)
Output:

['Organization', 'Industry', 'Employees']


['Google', 'IT', '1500']
['Microsoft', 'IT', '1300']
['Tata', 'Manufacturing', '1000']
['Tpoint Tech', 'Education', '200']
['Apple', 'IT', '1200']
Explanation:

In the above example, we imported the csv module and used the
'with open()' statement to open the [Link] file. We have then used
the [Link]() function in order to read the content from the CSV file. At
last, we printed the file content row-wise.

2) Using [Link]()
With the help of the [Link]() class, we can convert the CSV files into
dictionaries where field names work as keys. The filesystem offers us with
simple value field accessibility that makes the data more readable. This class
returns row data as dictionaries when running an iteration process.

Here is an example of the [Link]() class:

Example
1. import csv
2.
3. # opening the CSV file
4. with open('[Link]', newline='') as file:
5. # using the DictReader() class to convert the content of the file into a d
ictionary
6. reader = [Link](file)
7.
8. # printing each row of the table
9. for row in reader:
10. print(row)
Output:

{'Organization': 'Google', 'Industry': 'IT', 'Employees': '1500'}


{'Organization': 'Microsoft', 'Industry': 'IT', 'Employees': '1300'}
{'Organization': 'Tata', 'Industry': 'Manufacturing', 'Employees':
'1000'}
{'Organization': 'Tpoint Tech', 'Industry': 'Education', 'Employees':
'200'}
{'Organization': 'Apple', 'Industry': 'IT', 'Employees': '1200'}
Explanation:

In the above example, we have imported the csv module. We then used the
'with open()' statement to open the CSV file. After that, we have used the
DictReader() class from the csv module to turn each rows into a dictionary
through its column headers. At last, we printed the data in the dictionary
format.

3) Using pandas.read_csv()
Pandas, which uses NumPy, is an open-source library people use to easily
work with and analyze data. It helps with simplifying all these data handling
steps. The read_csv() function allows us to load CSV files as DataFrames,
helps save time and manage the information in a structured way.

Let us see an example.

Example
1. import pandas as pd
2.
3. # Reading the CSV file into a DataFrame
4. dframe = pd.read_csv('[Link]')
5.
6. # Displaying the DataFrame
7. print(dframe)
Output:

Organization Industry Employees


0 Google IT 1500
1 Microsoft IT 1300
2 Tata Manufacturing 1000
3 Tpoint Tech Education 200
4 Apple IT 1200
Explanation:

Here, we have imported the pandas library. We then used the read_csv()
function to convert the given CSV file into the DataFrame and stored it in a
variable. At last, we used the print statement to print DataFrame.

As a result, the CSV file is converted into rows and columns. This structure
makes it easier for us to understand the information from the CSV file.

Conclusion
Python is a versatile and powerful programming language that offers various
methods to read CSV files. In this tutorial, we learned some of these
methods. We discovered how the csv module and the pandas library help us
read CSV files. We learned about the different functions and classes of the
csv module that allow us to read the CSV files into different formats.
Similarly, the read_csv() function of the pandas library allow us view the CSV
file into the dictionary format.

You might also like