Problem Solving and Python Programming: UNIT V: Files, Modules, Packages

Files

Python Programming

Definition : File is a named location on the disk to store information.

Files        AU: Jan.-18, May-19, Dec.-19, Marks 16

Definition : File is a named location on the disk to store information.

File is used to store the information permanently.

 

1. Types of Files

There are two types of files

1. Text File

2. Binary File

1) Text File

• The text ASCII file is a simple file containing collection of characters that are readable to human.

• Various operations that can be performed on text files are - opening the file, reading the file, writing to the file, appending data to the file.

• The text file deals with the text stream.

• In text file each line contains any number of characters include one or more characters including a special character that denotes the end of file. Each line of the text have maximum 255 characters.

• When a data is written to the file, each newline character is converted to carriage return/ line feed character. Similarly when data is read from the file, each carriage return feed character is converted to newline character.

• Each line of data in the text file ends with newline character and each file ends with special character called EOF (i.e. End of File) character.

2) Binary File

• Binary file is a file which contains data encoded in binary form.

• This data is mainly used for computer storage or for processing purpose.

• The binary data can be word processing documents, images, sound, spreadsheets, videos, or any other executable programs.

• We can read text files easily as the contents of text file are ordinary strings but we can not easily read the binary files as the contents are in encoded form.

• The text file can be processed sequentially while binary files can be processed sequentially or randomly depending upon the need.

• Like text files, binary files also put EOF as an endmarker.

 

Difference between Text File and Binary File

Text File :

1. Data is present in the form of characters

2. The plain text is present in the file.

3. It can not be corrupted easily.

4. It can be opened and read using simple text editor like Notepad.

5. It have the extension such as py or .txt

Binary File

1. Data is present in the encoded form

2. The image, audio or text data can be present in the file.

3. Even if single bit is changed then the file gets corrupted.

4. It can not read using the text editor like Notepad.

5. It can have application defined extension,

 

2. Text Files

• The text files are type of files that store textual information.

• The text files are considered as persistent storages. That means once you store data in a text file that remains in it even-if you shutdown and restart the computer. One can be picked up where they left off.

• Various operations that can be performed on text files are :

1. Open file

2. Close file

3. Writing to the file

4. Reading from file

• Opening a file

In python there is a built in function open() to open a file.

Syntax

File_object=open(file_name,mode)

Where File_object is used as a handle to the file.

Example

F = open("test.txt")

Here file named test.txt is opened and the file object is in variable F

• We can open the file in text mode or in binary mode. There are various modes of a file in which it is opened. These are enlisted in the following table

Mode : Purpose

‘r’ - Open file for reading

‘w’ - Open file for writing. If the file is not created, then create new file and then write. If file is already existing then truncate it.

‘x’ - Open a file for creation only. If the file already exists, the operation fails.

‘a’ - Open the file for appending mode. Append mode is a mode in which the data is inserted at the end of existing text. A new file is created if it does not exist.

‘t’ - Opens the file in text mode

‘b’ - Opens the file in binary mode

‘+’ Opens a file for updation i.e. reading and writing.

For example :

Fo = open("test.txt", w) #opens a file in write mode

Fo = open("text.txt",rt) #Open a file for reading in text mode

• Closing a File

After performing all the file operations, it is necessary to close the file.

Closing of file is necessary because it frees all the resources that are associated with file.

Example –

fo = open("test.txt",rt)

fo.close() #closing a file.

 

3. Reading from Files

For reading the file , we must open the file in r mode and we must specify the correct file name which is to be read

The read() method is used for reading the file. For example -


Let us close this file and reopen it. Then call read statement inside the print statement, illustrated as follows –


 

Example 5.1.1 Write a Python program to read the contents of the file named 'test.txt

Solution :

ReadFile.py

inf = open('D:\\test.txt','rt')

print(inf.read())

inf.close()

Output

Introduction to File operations.

Reading and Writing file operations in Python are easy to understand.

We enjoy it.

This line is written to file.

This is the last line of the file.

>>>

Note that a blank line is returned when the file reaches the end of the file.

There some other useful methods for reading the contents of the file. Let us discuss them with the help of necessary illustrations

The readline() Method

The readline() method allows us to read a single line from the file. When file reaches to the end, it returns an empty string.

 

Example 5.1.2 Write a Python program to read and display first two lines of the text file.

Solution :

ReadLineDemo.py

inf = open('D:\\test.txt','rt')

print(inf.readline())

print(inf.readline())

inf.close()


Program Explanation : In above program,

1) The file is opened using open statement.

2) The we call readline() statements inside two subsequent print statement. After reading from the file using the readline() method, the control automatically passes to the next line. Hence we call readline() inside the print statement again.

3) Finally we must not forget to close the file using close() method.

The readLines() Method

The readLines() method is used to print all the lines in the program. Following program illustrates it –

ReadLines Demo.py

inf = open('D:\\test.txt','It')

print(inf.readlines())

inf.close()

Output

Introduction to File operations.

Reading and Writing file operations in Python are easy to understand.

We enjoy it.

This line is written to file.

This is the last line of the file.

>>> 

The list() Method

The list method is also used to display the contents of the file as a list. The program is as follows -

ListDemo.py

inf = open('D:\\test.txt','rt')

print(list(inf))

inf.close()

Output


Note that we passed the file object as an argument to the list method.

Displaying File using Loop

This is the most commonly used method of reading the file. In this method the contents of the file are read line by line using for loop.

 

Example 5.1.3 Write a program to display the contents of the file using for loop.

Solution :

DisplayFile.py

inf = open('D:\\test.txt', 'It')

for line in inf:

print(line)

inf.close()

Output

Introduction to File operations.

Reading and Writing file operations in Python are easy to understand.

We enjoy it.

This line is written to file.

This is the last line of the file.

>>> 

Opening a file using with

We can open the file using keyword with. The advantage of this is that the file gets closed properly after the read or write operations

OpenWith Demo.py

with open('D:\\test.txt','rt') as inf:

for line in inf:

print(line)

inf.close()

Output

Introduction to File operations.

Reading and Writing file operations in Python are easy to understand.

We enjoy it.

This line is written to file.

This is the last line of the file.

>>> Example

 

5.1.4 Write a Python program to find the line that starts with the word "This" from the following text which is stored in a file.

Test.txt

This is a python program

python is superb.

This is third line of program

this python program is nice

Solution :

FileDemo1.py

fh = open('d:\\test.txt')

i = 0 for line in fh:

line = line.rstrip()

if line.find('This')= =-1:continue

print(line)

Output


 

Example 5.1.5 Write a program in Python to split the text line written in the file into words.

Solution :

with open('d:\\test.txt', 'It') as inf:

line = inf.readline()

word_list=line.split()

print(word_list)

Output

['This', 'is', 'a', 'python', 'program')

>>> 

 

4. Writing to Files

• For writing the contents to the file, we must open it in writing mode. Hence we use 'w' or 'a' or 'x' as a file mode.

• The write method is used to write the contents to the file.

Syntax

File_object.write(contents)

• The write method returns number of bytes written.

• While using the 'w' mode in open, just be careful otherwise it will overwrite the already written contents. Hence in the next subsequent write commands we use “\n” so that the contents are written on the next lines in the file.

• For example:


The writelines() method

The writelines() method is used to write list of strings to the file. Following program illustrates this

 

Example 5.1.6 Write a python program to write multiple lines to a text file using writelines() method

Solution :

fo = open('d:\\test.txt','wt')

lines = ["Welcome to the Python programming\n","It is fun\n",

"Python is easy\n", "But it is powerful programming language"]

fo.writelines(lines)

fo.close()

Output

Now open the Notepad and open the test.txt file in it. It will be something like this


Appending the file

Appending the file means inserting records at the end of the file.

For appending the file we must open the file in 'a' or 'ab' mode.

For example

fo = open('d:\\test.txt', 'a')

fo.write("Python has a wide scope in future")

fo.close()

Output

Just open the existing d: \test.txt file to check the contents. It will be as follows -


 

Example 5.1.7 : Write a python program to write n number of lines to the file and display all these lines as output.

Solution :

print("How many lines you want to write")

n = int(input())

outFile=open("d:\\test.txt",'wt')

for i in range(n):

print("Enter line")

line = input()

outFile.write("\n"+line)

outFile.close()

print("The Contents of the file 'test.txt' are ...")

inFile=open("d:\\test.txt",'rt')

print(inFile.read())

inFile.close()

Output


 

Example 5.1.8 Write a python program to write the contents in 'one.txt' file. Read these contents and write them to another file named 'two.txt'

Solution :

print("How many lines you want to write")

n = int(input())

outFile = open("d:\\one.txt",'wt')

for i in range(n):

print("Enter line")

line=input()

outFile.write("\n"+line)

outFile.close()

inFile = open("d:\\one.txt",'It')

outFile=open("d:\\two.txt",'wt')

i = 0

for i in range(n+1):

line = inFile.readline()

outFile.write("\n"+line)

inFile.close()

outFile.close()

print("The Contents of the file 'two.txt' are ...")

inFile=open("d:\\two.txt",'rt')

print(inFile.read())

inFile.close()

 

Example 5.1.9 How to Merge multiple files in to a new file using Python.

AU: Dec.-19, Marks 6

Solution :

one = two = "

fp = open('d:\\first.txt','rt')

one = fp.read()

fp = open('d:\\second.txt','It')

second = fp.read()

one+ = "\n"

one+ = second

fp = open('d:\\third.txt','wt')

fp.write(one)

fp.close()

Output

Step 1: Create first.txt file using some text-editor like Notepad.


Step 2: Create second.txt file using some text-editor like Notepad.


Step 3: Now open the third.txt file using some text-editor. It will be as follows -


5. File Positions

The seek and tell method : The seek method is used to change the file position. Similarly the tell method returns the current position.

The method seek() sets the file's current position at the offset.

Syntax

fileObject.seek(offsets, whence])

Where

offset - This is the position of the read/write pointer within the file.

whence - This is optional and defaults to o which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

The method tell() returns the current position of the file read/write pointer within the file.

Syntax

fileObject.tell()

Programming Example

inf = open('d:\\test.txt','rt')

print("\tThe contents of the file are...")

print(inf.read())

print("\tThe current position is...")

print(inf.tell())#get current postion of file

inf.seek(0) #moves the file cursor to initial position

print("\tThe current position is...")

print(inf.tell())#get current position of file

Output


We can pass number of bytes to the seek method. These many bytes are skipped and then remaining contents are displayed. For example

>>> inf.seek(10)

10

>>> print(inf.read())

#note that 10 bytes are skipped and then the remaining contents are displayed

on to File Operations

Reading and writing operations in Python are easy

We enjoy it

This line is written in file

This is a last line of this file

>>> 

 

6. Format Operator

• The format operator is specified using % operator.

•  For example - if we want to display integer value then the format sequence must be %d, similarly if we want to display string value then the format sequence must be %s and so on.

•  Here is the illustration


• Various format specifiers are enlisted in the following table

Conversion : Meaning

d - Signed integer decimal.

i - Signed integer decimal.

u - Obsolete and equivalent to 'd', i.e. signed integer decimal.

x - Unsigned hexadecimal (lowercase),

X - Unsigned hexadecimal (uppercase).

e - Floating point exponential format (lowercase).

E - Floating point exponential format (uppercase).

f - Floating point decimal format.

F - Floating point decimal format.

g - Same as "e" if exponent is greater than - 4 or less than precision, "f" otherwise.

G - Same as "E" if exponent is greater than - 4 or less than precision, "F" otherwise,

c - Single character accepts integer or single character string).

r - String (converts any python object using repr()).

s - String (converts any python object using str()).

% - No argument is converted, results in a "%" character in the result.

• If there is more than one format sequence in the string, the second argument has to be a tuple. Each format sequence is matched with an element of the tuple, in order.

•  For example : Following errors are due to mismatch in tuple with format sequence.

>>> There are %d%d%d numbers'%(1,2) #mismatch in number of elements

TypeError : Not enough arguments for format string

>>> "There are %d rows'%'three'

TypeError: %d format: a number is required, not str   #mismatch in type of element

 

Example 5.5.10 Write a python program to display the name of the student, his course and age.

Solution :

name = 'Parth

course = 'Computer Engineering'

age = 18

print("Name = %s and course= %s and age = %d"%(name,course,age))

print("Name = %s and course= %s and age = %d"%('Anand','Mechanical Engineering',21))

Output

Name = Parth and course= Computer Engineering and age = 18

Name = Anand and course= Mechanical Engineering and age = 21

>>> 

 

7. Directory Methods

In this section we will discuss various directory methods.

1) Getting current working directory

For getting the name of current working directory we use the function named getcwd() method. This method returns the name of current working directory. For example –

getwdDemo.py

import os

print(os.getcwd())

Output


2) Displaying all the files and sub-directories inside a directory

For listing the contents of a directory we use the method listdir(). For example –

import os

print(os.listdir())

3) Creating a new directory

We can create a new directory using mkdir() method

mkdirDemo.py

import os

os.mkdir("mypython Programs") #creates a folder named mypython Programs

print(os.listdir()) #displaying the directory contents

4) Removing the directory or a file

A file can be deleted using remove() method.

The rmdir() method removes an empty directory

For example

import os os

remove("test.txt") #removes file test.txt

print(os.listdir()) #displays the directory contents

os.rmdir("mypython Programs") #removes the directory named 'mypython

Programs' print(os.listdir())#displays the directory contents

5) Renaming a File

A file can be renamed using the rename() method.

The first parameter to this method is the old file name and second parameter is the new file name.

For example

import os

os.rename('d:\\first.txt','one.txt')

Review Questions

1. Tabulate different modes for opening a file and explain the same. AU: Jan.-18, Marks 16

2. Explain about the file reading and writing operations using format operator with Python code AU : May-19, Marks 16

3. Explain the commands used to read and write into a file with examples. AU: Dec.-19, Marks 8

4. Discuss the use of format operator in file processing. AU : Dec.-19, Marks 8

5. Write methods to rename and delete files. AU : Dec.-19, Marks 2

 

Problem Solving and Python Programming: UNIT V: Files, Modules, Packages : Tag: Engineering Python : Python Programming - Files