Skip to main content

Python File Handling

Python File Handling

All programs need the input to process and output to display data. And everything needs a file as name storage compartments on computers that are managed by OS. Though variables provide us a way to store data while the program runs, but if we want out data to persist even after the termination of program, we have to save it to a file.

File and its path

There are always two parts of a file in computer system, the filename and its extension. Also the files have two key properties – its name and the location or path, which specifies the location where the file exists. The file name has two parts and they are separated by a dot (.) or period.
Figure – File and its path:
Directory Structure
A built-in open method is used to create a Python file-object, which provides a connection to the file that is residing on programmer’s machine. After calling the function open, programmers can transfer strings of data to and from the external file that is residing in the machine.

File Opening In Python

open() function is used to open a file in Python. It’s mainly required two arguments, first the file name and then file opening mode.
Syntax:
file_object = open(filename [,mode] [,buffering])
In the above syntax the parameters used are:
  • filename: It is the name of the file.
  • mode: It tells the program in which mode the file has to be open.
  • buffering: Here, if the value is set to zero (0), no buffering will occur while accessing a file, if the value is set to top one (1), line buffering will be performed while accessing a file.

Modes Of Opening File In Python

The file can be opened in the following modes:
Python File Opening Modes
ModeDescription
rOpens a file for reading only. (It’s a default mode.)
wOpens a file for writing. (If file doesn’t exist already, then it’s creates a new file, otherwise it’s truncate a file.)
xOpens a file for exclusive creation. (Operation fails if file does not exists in location.)
aOpens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in location.)
tOpens a file in text mode. (It’s a default mode.)
bOpens a file in binary mode.
+Opens a file for updating (reading and writing.)

File Object Attributes

If an attempt to open a file fails then open returns a false value, otherwise it returns a file object that provides various information related to that file.
Example:
#!/usr/bin/python

# file opening example in Python
fo
= open("sample.txt", "wb")
print "File Name: ", fo.name
print "Mode of Opening: ", fo.mode
print "Is Closed: ", fo.closed
print "Softspace flag : ", fo.softspace
Output:
File Name: sample.txt
Mode of Opening: wb
Is Closed: False
Softspace flag: 0

File Reading In Python

For reading and writing text data different text-encoding schemes are used such as ASCII (American Standard Code for Information Interchange), UTF-8 (Unicode Transformation Format), UTF-16.
Once a file is opened using open() method then it can be read by a method called read().
Example:
#!/usr/bin/python

# read the entire file as one string
with open('filename.txt') as f:
data
= f.read()

# Iterate over the lines of the File
with open('filename.txt') as f:
for line in f :
print(line, end=' ')
# process the lines

File Writing In Python

Similarly for writing data to files, we have to use open() with ‘wt‘ mode, clearing and overwriting the previous content. Also we have to use write() function to write into a file.
Example:
#!/usr/bin/python

# Write text data to a file
with open('filename.txt' , 'wt') as f:
f
.write ('hi there, this is a first line of file.\n')
f
.write ('and another line.\n')
Output:
hi there, this is a first line of file.
and another line.
By default, in Python – using the system default text encoding files are read/written. Though Python can understand several hundred text-encodings but the most common encoding techniques used are ASCII, Latin-1, UTF-8, UTF-16 etc. The use of ‘with’ statement in the example establishes a context in which the file will be used. As the control leaves the ‘with’ block, the file gets closed automatically.

Writing A File That Does Not Exists

The problem can be easily solved by using another mode – technique i.e. the ‘x‘ mode to open a file instead of ‘w‘ mode.
Let’s see two examples to differentiate among them.
Example:
#!/usr/bin/python

with open('filename' , 'wt') as f:
f
.write ('Hello, This is sample content.\n')

# This will create an error that the file 'filename' doesn't exist.

with open ('filename.txt' , 'xt') as f:
f
.write ('Hello, This is sample content.\n')
In binary mode, we should use ‘xb‘ instead of ‘xt‘.

Closing A File In Python

In Python, it is not system critical to close all your files after using them, because file will auto close after Python code finishes execution. You can close a file by using close() method.
Syntax:
file_object.close();
Example:

#!/usr/bin/python

try:
# Open a file
fo
= open("sample.txt", "wb")
# perform file operations
finally:
# Close opened file
fo
.close()



Comments

For Programs Click Here

Popular posts from this blog

C++ Constructors and Destructors

C++ Constructors and Destructors Providing the initial value as described in the earlier chapters of C++ does not conform to the philosophy of C++. So C++ provides a special member function called the constructor which enables an object to initialize itself at the time of its creation. This is known as automatic initialization of objects. This concept of C++ also provides another member function called destructor which is used to destroy the objects when they are no longer required. In this chapter, you will learn about how constructors and destructors work, types of constructors and how they can be implemented within C++ program. What are constructors? The process of creating and deleting objects in C++ is vital task. Each time an instance of a class is created the constructor method is called. Constructors is a special member functions of class and it is used to initialize the objects of its class. It is treated as a special member function because its name is the same as the cla...

Python Tutorial

               Python Tutorials             Python Tutorial Python is a general purpose object-oriented programming language with high-level programming capabilities. This Python tutorial series will help you to get started in Python programming language from scratch. Prerequisites To learn Python Programming Language you haven’t required any previous programming knowledge, but the basic understanding of any other programming languages will help you to understanding the Python Programming Concepts quickly. Python Programming Example A quick look at the example of  Hello, World!  in Python programming, and detailed description is given in the  Python Basics  page. Example: #!/usr/bin/python print "Hello, World!" Output: Hello, World! The above example has been used to print  Hello, World!  text on the screen.

Java Method Overriding

Java Method Overriding Declaring a method in the subclass which already exists there in the parent class is known as method overriding. When a class is inheriting a method from a superclass of its own, then there is an option of overriding the method provided it is not declared as final. The advantage of using overriding is the ability to classify a behavior that’s specific to the child class and the child class can implement a parent class method based on its necessity. There are certain rules that a programmer should follow in order to implement overriding. These are: In Java, a method can only be written in the child class and not in same class. Argument list should be exactly the same as that of the overridden method of that class. Instance methods can also be overridden if they are inherited by the child class. A constructor cannot be overridden. Final – declared methods cannot be overridden. Any method that is static cannot be used to override. The return type must have to be the...