SlideShare a Scribd company logo
1 of 14
Download to read offline
 
© Prof Mukesh N Tekwani, 2016 
 
 
Unit I Chap 1 : Python ­ File Input and Output 
 
I.1 Concept of a File:  
In all the programs we have seen so far, the data provided to a Python program was through                                   
the command line and it is not saved. If a program has to be run again, the user must again                                       
input data. Similarly, the output of a program appears on the computer screen but is not                               
saved anywhere permanently.   
 
In practical programming it is necessary to provide data to a program from a file, and save                                 
the output data into a file. The output data may be required for further processing. A file is a                                     
collection of data. This data may be, for example, students’ data (Roll No, Name, Address,                             
Tel No, Grades,...), employee data (EmpID, Name, Dept, Designation, Salary…), etc. A file                         
could also be used to store a picture (say the fingerprints of employees), audio, video, etc. 
 
I.2 Types of Files:  
There are many different types of files.  
(i) Text files   
(ii) audio files 
(iii) video files 
(iv) binary files 
(v) presentations (Microsoft PowerPoint presentation .pptx files) 
(vi) Word processor documents  (Microsoft Word .docx files), etc 
 
In this chapter we will study how Python handles text files. Text files contain only text                               
characters (alphabets, digits, mathematical symbols, and other readable characters.A text                   
file can be created and opened in any text editor such as Notepad. Text inside a text file                                   
cannot be formatted such as bold, italic, underline, font colors, styles etc. These files donot                             
contain any metadata such as page numbers, header, footer, etc. But text files are very                             
useful as they can store data which can be imported into various types of programs. Text                               
files are small in size and therefore easier and faster to process. Some examples of text                               
files are: files created with text editor such as Notepad, programs in programming languages                           
such as Python, C, C++, etc, HTML files, CSV files, etc. CSV stands for ​C​omma ​S​eparated                               
V​alue. In a CSV file, data is separated by using a comma between different items. For                               
example, a CSV text file containing student data looks like this: 
 
Name, Class, MajorSubject, Grade 
Amit, FYBSc, Physics, 1 
Nikhil, SYBCom, Accounts, 1 
Prerana, TYBSc, Chemistry, 2 
 
 
1  
 
© Prof Mukesh N Tekwani, 2016 
 
In this chapter we will study how to write Python programs that use text files to input and                                   
output data. 
  
I.3 Opening a file:  
For this exercise, create a folder called in C drive called: C:/37/Files. We will save all our                                 
programs for this chapter in this folder. 
 
In IDLE (​I​ntegrated ​D​evelopment and ​L​earning ​E​nvironment), select File → New File and                         
type the following three lines: 
This is Line 1 
This is Line 2 
This is Line 3 
 
Save this file as a text file with filename FileEx1.txt, in the folder you just created. 
 
Create a new program file in IDLE and save it with the filename FileReader1.py. This file                               
should also be saved in the folder C:37Files 
 
Program 1: FileReader1.py 
file = open("C:/37/files/FileEx1.txt", "r") 
contents = file.read() 
print(contents) 
file.close() 
 
Run this program and the output is as shown below: 
This is Line 1 
This is Line 2 
This is Line 3 
 
Analysis of the program: 
1. open() is a builtin function in Python. It opens a file; the  file cursor is used to keep 
information about the current location in the file, which part of the file has been read, 
and which part has yet to be read. Initially, the file cursor points to the beginning of 
the file but as we read the file, the file cursor begins to move forward.  
2. The first argument in the function open() is "C:/37/files/FileEx1.txt". It is the name of 
the file to open. The second argument is “r”, which means that the file has to be 
opened in read­only mode. Here, “r” is called as the file mode. Other file modes are 
“​w​” for ​writing​ to a file and “​a​” to ​append ​data to a file.  If file mode is omitted in the 
function call, it is assumed to  be “read only”. 
3. The second statement file.read() tells Python that you want to read the contents of 
the entire file into a string called ​contents​.  
4. The third statement print(contents), prints the string. 
 
2  
 
© Prof Mukesh N Tekwani, 2016 
 
5. The last statement is file.close(). It closes the file. Every file opened for 
reading/writing must be closed. 
 
The ​with​ statement: 
Every open file must be closed in Python. So we have to use two statements in every 
program like this: 
file = open(filename, mode) 
: 
: 
: 
file.close() 
 
In this code, the name ​file is a file handle. Python provides the ​with statement that                               
automatically closes a file when the end of the file is reached. 
 
General syntax: 
with open(filename, mode) as variable: 
processing block 
 
The complete program to read a text file is now : 
 
Program 2: FileReader2.py 
with open("C:/37/files/FileEx1.txt", "r") as file: 
    contents = file.read() 
 
print(contents) 
 
Output of the above program is the same as that for FileReader1.py 
I.4 Techniques for Reading Files:  
There are four techniques for reading a file and all these techniques work by starting at the                                 
current file cursor. 
 
1. Techniques for Reading a File : “The Read Technique”​: This techniques is                       
used to: 
(i) Read the contents of a file into a ​single string​, or 
(ii) To specify exactly how many characters to read. 
 
To read the contents of the file into a single string, we use the following syntax: 
while open(filename, mode) as file: 
contents = file.read() 
 
print (contents) 
 
3  
 
© Prof Mukesh N Tekwani, 2016 
 
This reads the entire file from the current cursor location to the end of the file, and then                                   
moves the cursor to the end of the file. 
 
To read a specific number of characters, we specify the number of characters to read as the                                 
argument to the read() function. For example, to read 10 characters from the beginning of                             
the file, the program is: 
 
Program 3:  
file = open("C:/37/files/FileEx1.txt", "r") 
contents = file.read(10) 
print(contents) 
file.close() 
 
The output of this program for the same input as shown below: 
This is Li 
>>>  
The cursor now points to the character after the 10th character. 
 
2. Techniques for Reading a File: “The Readlines Technique”​: This technique is                     
used to read ​each line ​of a text file and store it in a ​separate ​string. After reading the lines,                                       
the cursor moves to the end of the file. 
 
Program 4: FileReader5.py 
# Read the lines of a file into separate strings  
print ("This program reads the lines of a file into separate strings .") 
with open("C:/37/files/FileEx1.txt", "r") as file: 
    lines = file.readlines() 
 
print(lines) 
 
In this program, the statement print(lines) prints all the strings. Output of this program is : 
 
This program reads the lines of a file into separate strings . 
['This is Line 1n', 'This is Line 2n', 'This is Line 3n'] 
>>>  
 
Each line ends with the newline character ‘n’ . But the last line of a text file may not end with                                         
a ‘n’ character. 
 
To print only line no 2, we can modify the program as follows: 
 
Program 5:  
# Read the lines of a file into separate strings  
print ("This program reads the lines of a file into separate strings and prints only the 
 
4  
 
© Prof Mukesh N Tekwani, 2016 
 
second line.") 
with open("C:/37/files/FileEx1.txt", "r") as file: 
    lines = file.readlines() 
 
print(lines[1]) 
file.close() 
 
In the above program, the line print(lines[1]) prints only the 2nd line. Remember, indices start                             
at 0. 
 
What happens when we give an index number more than the number of lines? Try this                               
statement:  print(lines[10]). Now, we get an error as shown below  
This program reads the lines of a file into separate strings and prints only the second line. 
Traceback (most recent call last): 
  File "C:/37/files/FileReader5.py", line 6, in <module> 
    print(lines[10]) 
IndexError: list index out of range 
>>>  
 
Program 6: FileReader6.py 
This program prints the lines of a text file in reverse order. 
# Read the lines of a file into separate strings 
# Then print the lines in reverse order 
print ("This program reads the lines of a file into separate strings and prints them in 
reverse order.") 
with open("C:/37/files/FileEx2.txt", "r") as file: 
    lines = file.readlines() 
 
print(lines) 
 
for site in reversed(lines): 
    print(site.strip()) 
   
file.close() 
 
Assume the file FileEx2.txt contains the following lines: 
Google 
Microsoft 
IBM 
Infosys 
Wipro 
Capgemini 
 
This program reads the lines of a file into separate strings and prints them in reverse order. 
['Googlen', 'Microsoftn', 'IBMn', 'Infosysn', 'Wipron', 'Capgeminin'] 
Capgemini 
 
5  
 
© Prof Mukesh N Tekwani, 2016 
 
Wipro 
Infosys 
IBM 
Microsoft 
Google 
>>>  
 
Analysis: We have used the built­in function reversed() to reverse the items in the list. The                               
strip() method is used to remove all whitespace characters from the left and right of a string.                                 
We have used the strip() method without any arguments so it removes only whitespaces. 
To remove whitespace characters only from the ​left of a string use the method ​lstrip()​. To                               
remove whitespace characters only from the ​right​ of a string use the method ​rstrip()​.  
 
Run the following program and comment on the output: 
 
Program 7:  FileReader7.py 
Using the strip() method. 
# Read the lines of a file into separate strings 
# Then print the lines in reverse order 
 
print ("This program reads the lines of a file into separate strings and prints them in 
reverse order. What is the output? What happened to the ‘C’? Why is there a blank line 
between two lines in the o/p?") 
 
with open("C:/37/files/FileEx2.txt", "r") as file: 
    lines = file.readlines() 
 
print(lines) 
 
for site in reversed(lines): 
    print(site.strip('C')) 
   
file.close() 
 
Why is there a blank line between two lines? 
 
Program 8:  FileReader8.py 
Program to sort the lines of a text file. 
# Read the lines of a file into separate strings 
# Then print the lines in sorted order 
 
print ("This program reads the lines of a file into separate strings and prints them in sorted 
order.") 
 
with open("C:/37/files/FileEx2.txt", "r") as file: 
    lines = file.readlines() 
 
 
6  
 
© Prof Mukesh N Tekwani, 2016 
 
print("Original lines:") 
print(lines) 
 
print("Lines in sorted order:") 
for site in sorted(lines): 
    print(site.strip()) 
   
file.close() 
 
The built­in function sorted() is used to sort the lines and display them. Note that, there is no                                   
change made to the original text file. 
 
 
3. Techniques for Reading a File : “The For Line In File” Technique​: This                         
techniques is used to carry out the same action on each line of a file. Suppose we want to                                     
read a text file and print the length of each line i.e. number of characters in each line. Here is                                       
the program 
 
Program 9:  FileReader9.py 
Program to print the length of each line of a text file. 
# Read the lines of a file order and print the length of each line 
 
print ("This program reads the lines of a file and prints the length of each line.") 
 
with open("C:/37/files/FileEx2.txt", "r") as file: 
    for line in file: 
        print(line, len(line)) 
   
file.close() 
 
Output of this program is : 
This program reads the lines of a file and prints the length of each line. 
Google 
 7 
Microsoft 
 10 
IBM 
 4 
Infosys 
 8 
Wipro 
 6 
Capgemini 
 10 
>>>  
 
 
7  
 
© Prof Mukesh N Tekwani, 2016 
 
Observe that the length of each string is one more than the number of characters that can be                                   
seen. But each string is terminated by the newline character ‘n’ so that increases the size by                                 
one character.  
Modification: 
Make only this small change in the program and observe the output: 
print(line.strip(), len(line)) 
 
What is the output and why is it like that? 
 
Modification: 
No modify the print line as follows and comment on the output: 
print(line, len(line.strip()))  
 
4. Techniques for Reading a File : “The Readline” Technique​: This techniques is                       
used to read one entire line from a file. This line can then be processed.  
 
Program 10:  FileReader10.py 
Program to illustrate the use of readline() technique. 
 
A text file contains the following data about number of students in various academic years in                               
FYBSc.  
Filename: FileEx3.txt 
Number of students in various academic years in FYBSc 
#Year 2010­11 to 2015­16 
#Semester 1 
67 
69 
53 
58 
66 
61 
 
We have to count the total number of students in these academic years,  
with open("C:/37/files/FileEx3.txt", "r") as inpfile: 
    #Read the description line 
    file.readline() 
 
    #Keep reading the comment lines until we read the first piece of data 
    data = inpfile.readline().strip() 
    while data.startswith("#"): 
        data = inpfile.readline().strip() 
 
    #Now we have the first actual data item. Add it to total number of students 
    numofstudents = int(data) 
 
    #Read the rest of the file 
    for data in inpfile: 
 
8  
 
© Prof Mukesh N Tekwani, 2016 
 
        numofstudents = numofstudents + int(data) 
 
    print("Total number of students: ", numofstudents)   
 
I.5 Techniques for Writing Files:  
The built­in write() function is used to write data to a text file. The general syntax of write() is: 
file.write(string) 
 
The following program opens a file called FileEx4.txt and writes the words “I Love Python” to                               
the file and then closes the file. 
 
Program 11:  FileReader11.py 
Program to write a string to a text file. 
#Writing a file 
 
with open("C:/37/files/FileEx4.txt", "w") as optfile: 
    optfile.write("I Love Python") 
   
optfile.close() 
 
The file is now opened in write mode by using “w” as the mode. If the file FileEx4.txt already                                     
exists, it is overwritten with new data.If the filename does not exist, it is first created and then                                   
data written to it. 
 
Program 12:  FileReader12.py 
Program to write a the numbers 1 to 10, one per line  to a text file. 
#Writing the numbers 1 to 10 to a file 
 
with open("C:/37/files/FileEx5.txt", ​"w"​) as optfile: 
    for i in range(1, 11): 
        optfile.write(str(i)+ "n") 
   
optfile.close() 
 
Check the output of the file FileEx5.txt by opening it in a text editor. 
 
 
Program 13:  FileReader13.py 
Program to append data to a text file. 
The following program appends numbers from 11 to 20 to the file FileEx5.txt that we created                               
earlier. Data already stored in the file is not lost, and new data is added to the end of the file                                         
FileEx5.txt 
 
 
9  
 
© Prof Mukesh N Tekwani, 2016 
 
#Appending data to a file  
 
with open("C:/37/files/FileEx5.txt", ​"a"​) as optfile: 
    for i in range(11, 21): 
        optfile.write(str(i)+ "n") 
   
optfile.close() 
 
 
Program 14:  FileReader14.py 
Program to read data from a file, process it and write it to another file. 
A file FileEx6.txt contains the marks obtained by 5 students in two tests. These marks are                               
separated by a blank space. Write a program that reads the two marks for each student and                                 
stores these marks and their total in another file called Results.txt 
FileEx6.txt    Results.txt 
15 18 
17 22 
6 11 
21 25 
23 22 
  M1 M2 Total 
15 18 33 
17 22 39 
6 11 17 
21 25 46 
23 22 45 
 
 ​Program: 
# Read the contents of a file, process each line and write results to a new file   
print("Read the contents of a file, process the data and write result into another file")  
 
optfile = open("C:/37/files/Results.txt", "w") 
inpfile = open("C:/37/files/FileEx6.txt", "r")   
 
optfile.write("M1 M2 Totaln") 
 
for numpair in inpfile: 
    numpair = numpair.strip() 
    values = numpair.split() 
    total = int(values[0]) + int(values[1]) 
    optline = '{0} {1}n'.format(numpair, total) 
    optfile.write(optline) 
 
print("file written") 
print("now closing all files") 
 
optfile.close() 
inpfile.close() 
 
 
 
 
10  
 
© Prof Mukesh N Tekwani, 2016 
 
Program 15:  FileReader15.py 
Program to prompt the user for a file and display the contents of the file. 
#To prompt the user for a filename and display the contents of that file 
 
name = input("Enter the file name ") 
fname = open(name, "r") 
 
print("Contents of the file are : ") 
contents = fname.read() 
 
print(contents) 
 
fname.close() 
 
 
Program 16:  FileReader16.py 
Program to prompt the user for a filename and backup the file. 
# Write a program that makes a backup copy of your file 
 
#import the module os so that we can use functions from this module 
import os 
 
orgfile = input('Which file would you like to back­up? ') 
base, ext = os.path.splitext(orgfile) 
#print (base) 
#print(ext) 
 
new_filename = base + '.bak' 
backup = open(new_filename, 'w') 
 
orgfile = open(orgfile, "r") 
 
for line in orgfile: 
    backup.write(line) 
 
orgfile.close() 
backup.close() 
 
I.6 Manipulating Directories:  
Files are arranged in folders or directories. Every running program has a “current directory”.                           
Python searches for files in the default or current directory.  
 
Python has a module named ​os module which contains many functions for working with files                             
and directories. We now study some of these built­in functions of the ​os​ module. 
 
 
11  
 
© Prof Mukesh N Tekwani, 2016 
 
Program 17:  FileReader17.py 
Program to study directory manipulation. 
#Import the module os 
import os 
 
#Get the current working directory or relative path 
cwd = os.getcwd() 
print("Current working directory: ", cwd) 
 
#To get the absolute path names 
print("Absolute path: ", os.path.abspath('Results.txt')) 
 
#To check if a file or directory exists 
print("Does file exist: ", os.path.exists("Results.txt")) 
print("Does file exist: ", os.path.exists("Results.xls")) 
 
#To check if it is a directory 
print("Is it a directry: ", os.path.isdir("Results.txt")) 
print("Is it a directry: ", os.path.isdir("C:37files")) 
 
#To check if it is a file 
print("Is it a file: ", os.path.isfile("Results.txt")) 
 
#To return a  list of files and directories in a directory 
print("List of files and sub directories: ") 
print(os.listdir(cwd)) 
 
 
Practical Exercises 
1. Write a program to ignore the first 10 characters of a text file and print the remaining                                 
characters. 
2. Write a program that prompts the user for a file to display and then show the contents of                                   
the file. 
3. Write a program that makes a backup of a file. Your program should prompt the user for                                 
a file to copy and then write a new file with the same contents but with .bak as the file                                       
extension. 
4. Write a program that prints the length of each line in a text file. 
5. Develop a Python program that reads in any given text file and displays the number of                               
lines, words and total number of characters in the file including spaces and special                           
characters but not the newline character ‘n’.  
6. Develop a Python program that reads messages contained in a text file, and encodes the                             
messages saved in a new file. For encoding messages, a simple substitution key should                           
be used as shown : A­­>C, B → D, C → E, D → F, … etc. The unencrypted text file has                                           
the filename msgs.txt and the encrypted file has the same name but filename extension                           
is .enc 
7. Develop a Python program that reads encrypted messages contained in a text file, and                           
decodes the messages saved in a new file. For decoding messages, a simple                         
substitution key should be used as shown : C­­A, D → B, E→ C, F→ D, … etc. The                                     
 
12  
 
© Prof Mukesh N Tekwani, 2016 
 
encrypted text file has the filename msgs.enc and the decrypted file has the same name                             
but filename extension is .txt 
8. Write a Python program that reads a text file and prints each word on a separate line.  
9. A text file called marks contains the marks obtained by 20 students. Assume marks are                             
not repeated. Write a Python program to find and display the highest mark. 
10. Write a program that reads the first 10 characters of a text file but does not display them.                                   
The rest of the characters should be displayed, 
11. Write a program that prints the length of each line. The output should have this format: 
Line No                                 Length 
   1 
     2 
   : 
12. What is the output of the following program? 
f = None 
for i in range (5): 
    with open("data1.txt", "w") as f: 
        if i > 2: 
  break 
  print (f.closed) 
 
g = open("data2.txt", "w") 
 
for i in range (5): 
    if i > 2: 
        break 
  print (g.closed) 
 
 
 
 
   
 
13  
 
© Prof Mukesh N Tekwani, 2016 
 
Miscellaneous Questions 
 
1. Give an instruction in Python that opens a file named “Markss.txt” for reading and                           
assigns the identifier inpfile to the file object created. 
2. Give an instruction in Python that opens a file named “Results.txt” for writing and assigns                             
the identifier optfile to the file object created. 
3. Multiple Choice Questions: 
3.1. Which of the following statements are true? (multiple answers allowed) 
a) ​A. When you open a file for reading, if the file does not exist, an error occurs. 
b) When you open a file for reading, if the file does not exist, the program will open                                   
an empty file. 
c) When you open a file for writing, if the file does not exist, a new file is created. 
d) When you open a file for writing, if the file exists, the existing file is overwritten with                                   
the new file. 
Ans a, c, d 
 
 
   
 
14  

More Related Content

What's hot

What's hot (20)

Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
File operations in c
File operations in cFile operations in c
File operations in c
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
Python GUI
Python GUIPython GUI
Python GUI
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Lesson 02 python keywords and identifiers
Lesson 02   python keywords and identifiersLesson 02   python keywords and identifiers
Lesson 02 python keywords and identifiers
 
List in Python
List in PythonList in Python
List in Python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 

Viewers also liked

Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Wayne Jones Jnr
 

Viewers also liked (19)

Java chapter 3
Java   chapter 3Java   chapter 3
Java chapter 3
 
Html tables examples
Html tables   examplesHtml tables   examples
Html tables examples
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Html graphics
Html graphicsHtml graphics
Html graphics
 
Java chapter 3 - OOPs concepts
Java chapter 3 - OOPs conceptsJava chapter 3 - OOPs concepts
Java chapter 3 - OOPs concepts
 
Java swing 1
Java swing 1Java swing 1
Java swing 1
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Data Link Layer
Data Link Layer Data Link Layer
Data Link Layer
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Phases of the Compiler - Systems Programming
Phases of the Compiler - Systems ProgrammingPhases of the Compiler - Systems Programming
Phases of the Compiler - Systems Programming
 
Digital signal and image processing FAQ
Digital signal and image processing FAQDigital signal and image processing FAQ
Digital signal and image processing FAQ
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
Java misc1
Java misc1Java misc1
Java misc1
 
Data communications ch 1
Data communications   ch 1Data communications   ch 1
Data communications ch 1
 
Chap 3 data and signals
Chap 3 data and signalsChap 3 data and signals
Chap 3 data and signals
 
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File TransferChapter 26 - Remote Logging, Electronic Mail & File Transfer
Chapter 26 - Remote Logging, Electronic Mail & File Transfer
 
Introduction to systems programming
Introduction to systems programmingIntroduction to systems programming
Introduction to systems programming
 

Similar to Python reading and writing files

fileop report
fileop reportfileop report
fileop report
Jason Lu
 

Similar to Python reading and writing files (20)

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Python-files
Python-filesPython-files
Python-files
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Deletion of a Record from a File - K Karun
Deletion of a Record from a File - K KarunDeletion of a Record from a File - K Karun
Deletion of a Record from a File - K Karun
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
Data file handling
Data file handlingData file handling
Data file handling
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Data Science Process.pptx
Data Science Process.pptxData Science Process.pptx
Data Science Process.pptx
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File management in C++
File management in C++File management in C++
File management in C++
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
 
fileop report
fileop reportfileop report
fileop report
 

More from Mukesh Tekwani

More from Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 

Python reading and writing files

  • 1.   © Prof Mukesh N Tekwani, 2016      Unit I Chap 1 : Python ­ File Input and Output    I.1 Concept of a File:   In all the programs we have seen so far, the data provided to a Python program was through                                    the command line and it is not saved. If a program has to be run again, the user must again                                        input data. Similarly, the output of a program appears on the computer screen but is not                                saved anywhere permanently.      In practical programming it is necessary to provide data to a program from a file, and save                                  the output data into a file. The output data may be required for further processing. A file is a                                      collection of data. This data may be, for example, students’ data (Roll No, Name, Address,                              Tel No, Grades,...), employee data (EmpID, Name, Dept, Designation, Salary…), etc. A file                          could also be used to store a picture (say the fingerprints of employees), audio, video, etc.    I.2 Types of Files:   There are many different types of files.   (i) Text files    (ii) audio files  (iii) video files  (iv) binary files  (v) presentations (Microsoft PowerPoint presentation .pptx files)  (vi) Word processor documents  (Microsoft Word .docx files), etc    In this chapter we will study how Python handles text files. Text files contain only text                                characters (alphabets, digits, mathematical symbols, and other readable characters.A text                    file can be created and opened in any text editor such as Notepad. Text inside a text file                                    cannot be formatted such as bold, italic, underline, font colors, styles etc. These files donot                              contain any metadata such as page numbers, header, footer, etc. But text files are very                              useful as they can store data which can be imported into various types of programs. Text                                files are small in size and therefore easier and faster to process. Some examples of text                                files are: files created with text editor such as Notepad, programs in programming languages                            such as Python, C, C++, etc, HTML files, CSV files, etc. CSV stands for ​C​omma ​S​eparated                                V​alue. In a CSV file, data is separated by using a comma between different items. For                                example, a CSV text file containing student data looks like this:    Name, Class, MajorSubject, Grade  Amit, FYBSc, Physics, 1  Nikhil, SYBCom, Accounts, 1  Prerana, TYBSc, Chemistry, 2      1  
  • 2.   © Prof Mukesh N Tekwani, 2016    In this chapter we will study how to write Python programs that use text files to input and                                    output data.     I.3 Opening a file:   For this exercise, create a folder called in C drive called: C:/37/Files. We will save all our                                  programs for this chapter in this folder.    In IDLE (​I​ntegrated ​D​evelopment and ​L​earning ​E​nvironment), select File → New File and                          type the following three lines:  This is Line 1  This is Line 2  This is Line 3    Save this file as a text file with filename FileEx1.txt, in the folder you just created.    Create a new program file in IDLE and save it with the filename FileReader1.py. This file                                should also be saved in the folder C:37Files    Program 1: FileReader1.py  file = open("C:/37/files/FileEx1.txt", "r")  contents = file.read()  print(contents)  file.close()    Run this program and the output is as shown below:  This is Line 1  This is Line 2  This is Line 3    Analysis of the program:  1. open() is a builtin function in Python. It opens a file; the  file cursor is used to keep  information about the current location in the file, which part of the file has been read,  and which part has yet to be read. Initially, the file cursor points to the beginning of  the file but as we read the file, the file cursor begins to move forward.   2. The first argument in the function open() is "C:/37/files/FileEx1.txt". It is the name of  the file to open. The second argument is “r”, which means that the file has to be  opened in read­only mode. Here, “r” is called as the file mode. Other file modes are  “​w​” for ​writing​ to a file and “​a​” to ​append ​data to a file.  If file mode is omitted in the  function call, it is assumed to  be “read only”.  3. The second statement file.read() tells Python that you want to read the contents of  the entire file into a string called ​contents​.   4. The third statement print(contents), prints the string.    2  
  • 3.   © Prof Mukesh N Tekwani, 2016    5. The last statement is file.close(). It closes the file. Every file opened for  reading/writing must be closed.    The ​with​ statement:  Every open file must be closed in Python. So we have to use two statements in every  program like this:  file = open(filename, mode)  :  :  :  file.close()    In this code, the name ​file is a file handle. Python provides the ​with statement that                                automatically closes a file when the end of the file is reached.    General syntax:  with open(filename, mode) as variable:  processing block    The complete program to read a text file is now :    Program 2: FileReader2.py  with open("C:/37/files/FileEx1.txt", "r") as file:      contents = file.read()    print(contents)    Output of the above program is the same as that for FileReader1.py  I.4 Techniques for Reading Files:   There are four techniques for reading a file and all these techniques work by starting at the                                  current file cursor.    1. Techniques for Reading a File : “The Read Technique”​: This techniques is                        used to:  (i) Read the contents of a file into a ​single string​, or  (ii) To specify exactly how many characters to read.    To read the contents of the file into a single string, we use the following syntax:  while open(filename, mode) as file:  contents = file.read()    print (contents)    3  
  • 4.   © Prof Mukesh N Tekwani, 2016    This reads the entire file from the current cursor location to the end of the file, and then                                    moves the cursor to the end of the file.    To read a specific number of characters, we specify the number of characters to read as the                                  argument to the read() function. For example, to read 10 characters from the beginning of                              the file, the program is:    Program 3:   file = open("C:/37/files/FileEx1.txt", "r")  contents = file.read(10)  print(contents)  file.close()    The output of this program for the same input as shown below:  This is Li  >>>   The cursor now points to the character after the 10th character.    2. Techniques for Reading a File: “The Readlines Technique”​: This technique is                      used to read ​each line ​of a text file and store it in a ​separate ​string. After reading the lines,                                        the cursor moves to the end of the file.    Program 4: FileReader5.py  # Read the lines of a file into separate strings   print ("This program reads the lines of a file into separate strings .")  with open("C:/37/files/FileEx1.txt", "r") as file:      lines = file.readlines()    print(lines)    In this program, the statement print(lines) prints all the strings. Output of this program is :    This program reads the lines of a file into separate strings .  ['This is Line 1n', 'This is Line 2n', 'This is Line 3n']  >>>     Each line ends with the newline character ‘n’ . But the last line of a text file may not end with                                          a ‘n’ character.    To print only line no 2, we can modify the program as follows:    Program 5:   # Read the lines of a file into separate strings   print ("This program reads the lines of a file into separate strings and prints only the    4  
  • 5.   © Prof Mukesh N Tekwani, 2016    second line.")  with open("C:/37/files/FileEx1.txt", "r") as file:      lines = file.readlines()    print(lines[1])  file.close()    In the above program, the line print(lines[1]) prints only the 2nd line. Remember, indices start                              at 0.    What happens when we give an index number more than the number of lines? Try this                                statement:  print(lines[10]). Now, we get an error as shown below   This program reads the lines of a file into separate strings and prints only the second line.  Traceback (most recent call last):    File "C:/37/files/FileReader5.py", line 6, in <module>      print(lines[10])  IndexError: list index out of range  >>>     Program 6: FileReader6.py  This program prints the lines of a text file in reverse order.  # Read the lines of a file into separate strings  # Then print the lines in reverse order  print ("This program reads the lines of a file into separate strings and prints them in  reverse order.")  with open("C:/37/files/FileEx2.txt", "r") as file:      lines = file.readlines()    print(lines)    for site in reversed(lines):      print(site.strip())      file.close()    Assume the file FileEx2.txt contains the following lines:  Google  Microsoft  IBM  Infosys  Wipro  Capgemini    This program reads the lines of a file into separate strings and prints them in reverse order.  ['Googlen', 'Microsoftn', 'IBMn', 'Infosysn', 'Wipron', 'Capgeminin']  Capgemini    5  
  • 6.   © Prof Mukesh N Tekwani, 2016    Wipro  Infosys  IBM  Microsoft  Google  >>>     Analysis: We have used the built­in function reversed() to reverse the items in the list. The                                strip() method is used to remove all whitespace characters from the left and right of a string.                                  We have used the strip() method without any arguments so it removes only whitespaces.  To remove whitespace characters only from the ​left of a string use the method ​lstrip()​. To                                remove whitespace characters only from the ​right​ of a string use the method ​rstrip()​.     Run the following program and comment on the output:    Program 7:  FileReader7.py  Using the strip() method.  # Read the lines of a file into separate strings  # Then print the lines in reverse order    print ("This program reads the lines of a file into separate strings and prints them in  reverse order. What is the output? What happened to the ‘C’? Why is there a blank line  between two lines in the o/p?")    with open("C:/37/files/FileEx2.txt", "r") as file:      lines = file.readlines()    print(lines)    for site in reversed(lines):      print(site.strip('C'))      file.close()    Why is there a blank line between two lines?    Program 8:  FileReader8.py  Program to sort the lines of a text file.  # Read the lines of a file into separate strings  # Then print the lines in sorted order    print ("This program reads the lines of a file into separate strings and prints them in sorted  order.")    with open("C:/37/files/FileEx2.txt", "r") as file:      lines = file.readlines()      6  
  • 7.   © Prof Mukesh N Tekwani, 2016    print("Original lines:")  print(lines)    print("Lines in sorted order:")  for site in sorted(lines):      print(site.strip())      file.close()    The built­in function sorted() is used to sort the lines and display them. Note that, there is no                                    change made to the original text file.      3. Techniques for Reading a File : “The For Line In File” Technique​: This                          techniques is used to carry out the same action on each line of a file. Suppose we want to                                      read a text file and print the length of each line i.e. number of characters in each line. Here is                                        the program    Program 9:  FileReader9.py  Program to print the length of each line of a text file.  # Read the lines of a file order and print the length of each line    print ("This program reads the lines of a file and prints the length of each line.")    with open("C:/37/files/FileEx2.txt", "r") as file:      for line in file:          print(line, len(line))      file.close()    Output of this program is :  This program reads the lines of a file and prints the length of each line.  Google   7  Microsoft   10  IBM   4  Infosys   8  Wipro   6  Capgemini   10  >>>       7  
  • 8.   © Prof Mukesh N Tekwani, 2016    Observe that the length of each string is one more than the number of characters that can be                                    seen. But each string is terminated by the newline character ‘n’ so that increases the size by                                  one character.   Modification:  Make only this small change in the program and observe the output:  print(line.strip(), len(line))    What is the output and why is it like that?    Modification:  No modify the print line as follows and comment on the output:  print(line, len(line.strip()))     4. Techniques for Reading a File : “The Readline” Technique​: This techniques is                        used to read one entire line from a file. This line can then be processed.     Program 10:  FileReader10.py  Program to illustrate the use of readline() technique.    A text file contains the following data about number of students in various academic years in                                FYBSc.   Filename: FileEx3.txt  Number of students in various academic years in FYBSc  #Year 2010­11 to 2015­16  #Semester 1  67  69  53  58  66  61    We have to count the total number of students in these academic years,   with open("C:/37/files/FileEx3.txt", "r") as inpfile:      #Read the description line      file.readline()        #Keep reading the comment lines until we read the first piece of data      data = inpfile.readline().strip()      while data.startswith("#"):          data = inpfile.readline().strip()        #Now we have the first actual data item. Add it to total number of students      numofstudents = int(data)        #Read the rest of the file      for data in inpfile:    8  
  • 9.   © Prof Mukesh N Tekwani, 2016            numofstudents = numofstudents + int(data)        print("Total number of students: ", numofstudents)      I.5 Techniques for Writing Files:   The built­in write() function is used to write data to a text file. The general syntax of write() is:  file.write(string)    The following program opens a file called FileEx4.txt and writes the words “I Love Python” to                                the file and then closes the file.    Program 11:  FileReader11.py  Program to write a string to a text file.  #Writing a file    with open("C:/37/files/FileEx4.txt", "w") as optfile:      optfile.write("I Love Python")      optfile.close()    The file is now opened in write mode by using “w” as the mode. If the file FileEx4.txt already                                      exists, it is overwritten with new data.If the filename does not exist, it is first created and then                                    data written to it.    Program 12:  FileReader12.py  Program to write a the numbers 1 to 10, one per line  to a text file.  #Writing the numbers 1 to 10 to a file    with open("C:/37/files/FileEx5.txt", ​"w"​) as optfile:      for i in range(1, 11):          optfile.write(str(i)+ "n")      optfile.close()    Check the output of the file FileEx5.txt by opening it in a text editor.      Program 13:  FileReader13.py  Program to append data to a text file.  The following program appends numbers from 11 to 20 to the file FileEx5.txt that we created                                earlier. Data already stored in the file is not lost, and new data is added to the end of the file                                          FileEx5.txt      9  
  • 10.   © Prof Mukesh N Tekwani, 2016    #Appending data to a file     with open("C:/37/files/FileEx5.txt", ​"a"​) as optfile:      for i in range(11, 21):          optfile.write(str(i)+ "n")      optfile.close()      Program 14:  FileReader14.py  Program to read data from a file, process it and write it to another file.  A file FileEx6.txt contains the marks obtained by 5 students in two tests. These marks are                                separated by a blank space. Write a program that reads the two marks for each student and                                  stores these marks and their total in another file called Results.txt  FileEx6.txt    Results.txt  15 18  17 22  6 11  21 25  23 22    M1 M2 Total  15 18 33  17 22 39  6 11 17  21 25 46  23 22 45     ​Program:  # Read the contents of a file, process each line and write results to a new file    print("Read the contents of a file, process the data and write result into another file")     optfile = open("C:/37/files/Results.txt", "w")  inpfile = open("C:/37/files/FileEx6.txt", "r")      optfile.write("M1 M2 Totaln")    for numpair in inpfile:      numpair = numpair.strip()      values = numpair.split()      total = int(values[0]) + int(values[1])      optline = '{0} {1}n'.format(numpair, total)      optfile.write(optline)    print("file written")  print("now closing all files")    optfile.close()  inpfile.close()          10  
  • 11.   © Prof Mukesh N Tekwani, 2016    Program 15:  FileReader15.py  Program to prompt the user for a file and display the contents of the file.  #To prompt the user for a filename and display the contents of that file    name = input("Enter the file name ")  fname = open(name, "r")    print("Contents of the file are : ")  contents = fname.read()    print(contents)    fname.close()      Program 16:  FileReader16.py  Program to prompt the user for a filename and backup the file.  # Write a program that makes a backup copy of your file    #import the module os so that we can use functions from this module  import os    orgfile = input('Which file would you like to back­up? ')  base, ext = os.path.splitext(orgfile)  #print (base)  #print(ext)    new_filename = base + '.bak'  backup = open(new_filename, 'w')    orgfile = open(orgfile, "r")    for line in orgfile:      backup.write(line)    orgfile.close()  backup.close()    I.6 Manipulating Directories:   Files are arranged in folders or directories. Every running program has a “current directory”.                            Python searches for files in the default or current directory.     Python has a module named ​os module which contains many functions for working with files                              and directories. We now study some of these built­in functions of the ​os​ module.      11  
  • 12.   © Prof Mukesh N Tekwani, 2016    Program 17:  FileReader17.py  Program to study directory manipulation.  #Import the module os  import os    #Get the current working directory or relative path  cwd = os.getcwd()  print("Current working directory: ", cwd)    #To get the absolute path names  print("Absolute path: ", os.path.abspath('Results.txt'))    #To check if a file or directory exists  print("Does file exist: ", os.path.exists("Results.txt"))  print("Does file exist: ", os.path.exists("Results.xls"))    #To check if it is a directory  print("Is it a directry: ", os.path.isdir("Results.txt"))  print("Is it a directry: ", os.path.isdir("C:37files"))    #To check if it is a file  print("Is it a file: ", os.path.isfile("Results.txt"))    #To return a  list of files and directories in a directory  print("List of files and sub directories: ")  print(os.listdir(cwd))      Practical Exercises  1. Write a program to ignore the first 10 characters of a text file and print the remaining                                  characters.  2. Write a program that prompts the user for a file to display and then show the contents of                                    the file.  3. Write a program that makes a backup of a file. Your program should prompt the user for                                  a file to copy and then write a new file with the same contents but with .bak as the file                                        extension.  4. Write a program that prints the length of each line in a text file.  5. Develop a Python program that reads in any given text file and displays the number of                                lines, words and total number of characters in the file including spaces and special                            characters but not the newline character ‘n’.   6. Develop a Python program that reads messages contained in a text file, and encodes the                              messages saved in a new file. For encoding messages, a simple substitution key should                            be used as shown : A­­>C, B → D, C → E, D → F, … etc. The unencrypted text file has                                            the filename msgs.txt and the encrypted file has the same name but filename extension                            is .enc  7. Develop a Python program that reads encrypted messages contained in a text file, and                            decodes the messages saved in a new file. For decoding messages, a simple                          substitution key should be used as shown : C­­A, D → B, E→ C, F→ D, … etc. The                                        12  
  • 13.   © Prof Mukesh N Tekwani, 2016    encrypted text file has the filename msgs.enc and the decrypted file has the same name                              but filename extension is .txt  8. Write a Python program that reads a text file and prints each word on a separate line.   9. A text file called marks contains the marks obtained by 20 students. Assume marks are                              not repeated. Write a Python program to find and display the highest mark.  10. Write a program that reads the first 10 characters of a text file but does not display them.                                    The rest of the characters should be displayed,  11. Write a program that prints the length of each line. The output should have this format:  Line No                                 Length     1       2     :  12. What is the output of the following program?  f = None  for i in range (5):      with open("data1.txt", "w") as f:          if i > 2:    break    print (f.closed)    g = open("data2.txt", "w")    for i in range (5):      if i > 2:          break    print (g.closed)                13  
  • 14.   © Prof Mukesh N Tekwani, 2016    Miscellaneous Questions    1. Give an instruction in Python that opens a file named “Markss.txt” for reading and                            assigns the identifier inpfile to the file object created.  2. Give an instruction in Python that opens a file named “Results.txt” for writing and assigns                              the identifier optfile to the file object created.  3. Multiple Choice Questions:  3.1. Which of the following statements are true? (multiple answers allowed)  a) ​A. When you open a file for reading, if the file does not exist, an error occurs.  b) When you open a file for reading, if the file does not exist, the program will open                                    an empty file.  c) When you open a file for writing, if the file does not exist, a new file is created.  d) When you open a file for writing, if the file exists, the existing file is overwritten with                                    the new file.  Ans a, c, d            14