What is a File?
A file in itself is a bunch of bytes stored on some storage devices like hard-disk, pen-drive etc.
Each file is created in a specific format giving a particular name called file name.
File in Python
In Python Data file can be stored in two ways :
1. Text Files - A file consists of a sequence of lines. Text file stores information in the form of ASCII or UNICODE character. Unicode as well. In a text file, each line is terminated by a special character, known as End of Line (EOL). By default, this EOL charctr in the newline charcter(‘\n’) For example text.txt
2. Binary Files - Binary files used to store binary data such as images, video files, audio files etc.
In binary files, there is no delimiter for a line. Also, no character translations can be carried out in a binary file. As a result, binary files are easier and much faster than text file for carrying out reading and writing operation on data.
3. CSV files – CSV(Comma Separated values) is a simple flat file in a human readable format which is extensively used to store tabular data, in a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain Files in CSV format
Advantage of Data files:
When a data file to created, it provides the following advantages:
1. The stored data resides permanently in the hard disk unless erased by the user.
2. The stored data can be shared with similar type of files
3. It is always possible to update the data as per our need.
Working with Text File in Python
The different tasks that take place during file operations are maintained below:
1. Opening a File
2. Closing a File
3. Writing Data into a File
4. Reading Data from File
Opening a file
To open a file in Python, we use the open() function. The syntax
of open() is as follows:
file_object= open(file_name, access_mode)
The file_object has certain attributes that tells us basic
information about the file, such as:
<file.closed> -returns true if the file is closed and false otherwise.
<file.mode>- returns the access mode in which the file was opened.
<file.name>- returns the name of the file.
Files Modes
File Mode |
Description |
File Offset position |
<r> |
Opens the file in read-only mode. |
Beginning of the file |
<rb> |
Opens the file in binary and read-only mode. |
Beginning of the file |
<r+> or <+r> |
Opens the file in both read and write mode. |
Beginning of the file |
<w> |
Opens the file in write mode. If the file already exists, all the contents will be overwritten. If the file doesn’t exist, then a new file will be created. |
Beginning of the file |
<wb+> or |
Opens the file
in read, write and binary mode. If the file |
Beginning of the file |
<a> |
Opens the file in append mode. If the file doesn’t exist, then a new file will be created. |
End of the file |
<a+> or <+a> |
Opens the file
in append and read mode. If the file doesn’t |
End of the file |
Consider the following example.
myObject=open(“myfile.txt”, “a+”)
Closing a file
Once we are done with the read/write
operations on a file, it is a good practice to close the file. Python provides
a close() method to do so. While closing a file, the system frees the memory
allocated to it. The syntax of close() is:
file_object.close()
Here, file_object is the object that was returned while opening the file.
Opening a file using with clause
In Python, we can also open a file using with clause. The syntax of with clause is:
with open (file_name, access_mode) as file_ object:
The advantage of using with clause is that any file that is opened using this clause is closed automatically, once the control comes outside the with clause. In case the user forgets to close the file explicitly or if an exception occurs, the file is closed automatically. Also, it provides a simpler syntax.
with open(“myfile.txt”,”r+”) as myObject:
content = myObject.read()
Here, we don’t have to close the file explicitly using close() statement. Python will automatically close the file.
WRITING TO A TEXT FILE
WRITING TO A TEXT FILE For writing to a file, we first need to open it in write or append mode. If we open an existing file in write mode, the previous data will be erased, and the file object will be positioned at the beginning of the file. On the other hand, in append mode, new data will be added at the end of the previous data as the file object is at the end of the file. After opening the file, we can use the following methods to write data in the file.
• write() - for writing a single string to store it in the text file
• writelines() - for writing a sequence of strings
The write() method
write() method takes a string as an argument and writes it to the text file. It returns the number of characters being written on single execution of the write() method. Also, we need to add a newline character (\n) at the end of every sentence to mark the end of line.
Example
myobject=open("myfile.txt",'w')
myobject.write("Hey I have started using files in Python\n")
myobject.write("We are writing \ndata to a \ntext file \n")
marks=58
myobject.write(str(marks))
myobject.close()
Note: ‘\n’ is treated as a single character
Example :
fw=open(“Name.txt”, “w”)
fw.write(“Abbhiraj Kumar”)
fw.write(“Ravi Sharma”)
fw.write(“Manoj Kumar”)
fw.write(“Dhyan Chand”)
fw.close()
Example : the above code write data into a text file can also be developed by using loop. It is illustrated as:
Fw= open("Name.txt", 'w')
for a in range(5):
nm=input("Enter Name : ")
Fw.write(nm+"\n")
Fw.close()
The writelines() method
This method is used to write multiple strings to a file. We need to pass an iterable object like lists, tuple, etc. containing strings to the writelines() method. Unlike write(), the writelines() method does not return the number of characters written in the file. The following code explains the use of writelines().
Example:
Company=['Dell\n', 'HP\n', 'Samsung\n', 'Lenovo\n', 'Acer\n']
fw=open("Computer.txt", "w")
fw.writelines(Company)
fw.close()
Example : to store name and total marks of five students.
MyList=[]
fw=open("Student.txt","w")
for a in range(5):
nm=input("Enter name : ")
m=input("Enter total marks : ")
MyList.append(nm+" "+m+"\n")
fw.writelines(MyList)
fw.close()
READING FROM A TEXT FILE
We can write a program to read the contents of a file. Before reading a file, we must make sure that the file is opened in “r”, “r+”, “w+” or “a+” mode. There are three ways to read the contents of a file:
Following steps must be taken while reading data from a file.
· Open the file in read mode.
· Define the name of file with the extension
· Set the path to file (optional).
Python uses three different methods for reading data from a file as mentioned below:
Method |
Description |
Example |
a) read |
To read the entire data from the file;
starts reading from the cursor up to the end of the file. |
>>>
myobject=open("myfile.txt",'r') >>> print(myobject.read()) Hello everyone Writing multiline strings This is the third line >>> myobject.close() |
b) read([n]) |
To read 'n' characters from the file,
starting from the cursor. If the file holds fewer than 'n' characters, it
will read until the end of the file. |
>>>myobject=open("myfile.txt",'r')
>>> myobject.read(10)
'Hello ever' >>> myobject.close() |
c) readline([n]) |
To read only one line from the file, starts
reading from the cursor up to, and including, the end of line character. |
>>> myobject=open("myfile.txt",'r') >>> myobject.readline(10)
'Hello ever' >>> myobject.close() |
d) readlines() |
To read all lines from the file into a list,
starts reading from the cursor up to the end of the file and returns a list
of lines, separated by new line character '\n' |
>>>
myobject=open("myfile.txt", 'r') >>>
print(myobject.readlines()) ['Hello everyone\n', 'Writing multiline
strings\n', 'This is the third line'] >>> myobject.close() |
e) readable() |
It returns true if the file is readable. |
|
(a) read([n]) (b) readline([n]) (c) readlines()
(a) read() - It is used to read the entire data or content of the file. It means it start reading from the beginning up to the end of the file.
Example: When number of bytes(n) is specified in the read mode.
fr=open('Computer.txt', 'r')
print('Reading bytes from the file.')
str=fr.read()
print(str)
fr.close()
Output:
Example: When number of bytes (n) is specified continuously in two different lines in the read mode.
fr=open('Computer.txt', 'w')
st=input("Enter text :")
fr.write(st)
fr=open('Computer.txt', 'r')
print('Reading bytes from the file.')
str1=fr.read(7)
str2=fr.read(10)
print(str1)
print(str2)
fr.close()
Output:
Example: When number of byte(n) is specified in two different lines and each time reads from the first byte of the text.
fr=open('Computer.txt', 'w')
st=input("Enter text :")
fr.write(st)
fr=open('Computer.txt', 'r')
print('Reading bytes from the file.')
str1=fr.read(7)
print(str1)
fr.close()
fr=open('Computer.txt', 'r')
str2=fr.read(17)
print(str2)
fr.close()
Output:
(b) readline() :
It is used to read only one line (byte by byte) from the file at a time. However, if the number of bytes are specified then it reads only the number of specified bytes of the line from the file.
Example: To read first three lines from the file.
fr=open('Computer.txt', 'r')
print('Reading bytes from the file.')
str1=fr.readline()
str2=fr.readline()
str3=fr.readline()
print(str1)
print(str2)
print(str3)
fr.close()
Output:
Example: The same task can also be performed by using for loop or while loop.
fr=open('Computer.txt', 'r')
for a in range(3):
str1=fr.readline()
print(str1, end='')
fr.close()
Output:
In case we want to display each word of a line separately as an element of a list, then we can use split() function. The following code demonstrates the use of split() function.
>>> myobject=open("myfile.txt",'r')
>>> d=myobject.readlines()
>>> for line in d: words=line.split() print(words)
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements of a list. However, if splitlines() is used instead of split(), then each line is returned as element of a list, as shown in the output below:
>>> for line in d:
words=line.splitlines()
print(words)
Output
['Hello everyone']
['Writing multiline strings']
['This is the third line']
Let us now write a program that accepts a string from the user and writes it to a text file. Thereafter, the same program reads the text file and displays it on the screen.
Appending To file:
“Open for writing, end if it exists, then append data to the end of the file.”
In Python, we can use the ‘a’ mode to open an output file in append mode. This means that:
· If the file already exists, it will not be erased. If the file does not exist, it will be created.
· When data is written to the file, it will be written at the end of the file’s current contents.
Syntax:
<file_object> = open(<filename>, “a”)
Example
fapp=open("Computer.txt", "a")
print("Enter two name in the existing file :")
for b in range(2):
nm=input("Enter name :")
fapp.write(nm+"\n")
fapp.close()
Output:
Example : Read the entire content after appending new records
fr=open("Computer.txt", 'r')
rec = True
while rec:
rec=fr.readline()
print(rec, end='')
fr.close()
Output:
No comments:
Post a Comment