Files
Files
errors and exceptions, handling exceptions, modules, packages; Illustrative programs: word count,
Where,
File_name🡪 It is a string value which contains the name of the file to
access
Access_mode🡪 Determines the mode (read, write, append, etc.) in
which the file has to be opened.
Modes of File
• r🡪default mode for opening a file in read only format
• rb🡪read only purpose in binary format
• r+🡪Both read and write in text format
• rb+🡪Read and Write in binary format
• w🡪 write in text format
• wb🡪write only purpose in binary format
• w+🡪Reading and Writing in text format
• wb+🡪Reading and Writing in binary format
• a🡪appending the data to the file
• ab🡪appending the data in binary format
• a+🡪 Both appending and reading data to and from the file
• ab+🡪appending and reading data in binary format
• The text mode returns strings when reading from the file.
• The binary mode returns bytes and this mode is used when dealing
with non-text files like image or exe file.
Example
# Open file in read mode, the default mode:
>>>file = open(“sample.txt”)
>>>file = open(“sample.txt”,’w’) #write mode
>>>file = open(“sam.bmp”,’rb+’) # Read & files in binary mode
>>> file = open(“sample.txt”,mode=‘r’,encoding=‘utf-8’)
File Object Attributes
Attribute Returns
file.name File Name
file.mode The access mode to open file (r, w,r+,etc.,)
file.closed It returns True, if closed and False otherwise
Example
p=open("sample.txt",'w') Output:
print("File Name:",p.name) File Name: sample.txt
print("Closed or Opened:",p.closed) Closed or Opened: False
print("Mode of opening file:",p.mode) Mode of opening file: w
Writing to a file
The write() is used to write a string or sequence of bytes. It returns the
number of characters written in the file.
Open a file 🡪write ‘w’,append ‘a’
If the file already exists, the file will be overwritten
Syntax:
fileObject.write(str)
Example
p=open("sample1.txt","w") Output:
p.write("Information Technology \n")
p.write("Velammal College of
Engineering and Technology\n")
p.write("Madurai")
p.close()
Read Data from a File
Methods Explanation
Read([size]) It returns the specified number of characters from the
file
Readline() Returns the next line of the file
Readlines() Reads all the lines as list of strings in file
f=open("sample1.txt","r")
f.read(5)
'Infor'
f.read(6)
'mation'
f.read()
' Technology \nVelammal College of Engineering and Technology\nMadurai'
f.read()
''
f=open("sample1.txt","r")
f.readline()
'Information Technology \n'
f.readline()
'Velammal College of Engineering and Technology\n'
f.readlines()
['Madurai']
Closing a file
• In close() method, a file object flushes all information and closes the
file object.
• No more updations can be performed
• Syntax:
fileObject.close()
Example
p=open("sample1.txt","w")
print("Name of file:",p.name)
p.write("Information Technology \n")
p.write("Velammal College of Engineering and Technology\n")
p.write("Madurai")
p.close()
print("File Closed")
Output
Name of file: sample1.txt
File Closed
Appending Data to a file
• To append a new text to the existing file , we have to reopen the file
on append mode with ‘a’.
Syntax:
fileObject.open(“filename”,”a”)
import os
p=open("sam.txt","a")
file_size=os.path.getsize("sam.txt")
print(file_size)
p.truncate(40)
file_size2=os.path.getsize("sam.txt")
print(file_size2)
p.close()
File.write(str)
• The write() method writes a string to the given file.
• Syntax: fileObject.write(str)
• Code:
Fileobj=open(“sample.txt”,”w”)
Fileobj.write(“New line gets added \n”)
Fileobj.close()
Output:
Writelines()
• This method writes a sequence of strings into a file.
• The sequence can be any iterable object which produces a list of strings.
• Syntax: fileObject.writelines(sequence)
• Where, sequence🡪sequence of string
• Code:
import os
p=open("sam.txt","a")
seq=["\n","College of\n","Engineering and Technology"]
p.writelines(seq)
p.close()
Output
Next()
• The next() method is used in a file when it acts as an iterator in a loop.
• It will be called repeatedly.
• Syntax: fileObject.next()
Format Operator
Command Line Arguments
• Python command line • Input()🡪STRING
arguments are input parameters • Another way to accept the
passed to the script/program inputs other than inpu()
when executing them.
• Inputs will be passed to the
• Almost all programming programs as an arguments from
language provide support for COMMAND PROMPT
command line arguments.
• sys module
Execute:
Write Program
Save with .py extension
Open Command Prompt
Change the path to where the program is
being saved
Py filename.py arg1 arg2 arg3…..
• The function python sys module provides us to interact with the
interpreter.
• The python sys module provides access to any command-line
arguments via the sys.argv.
• Sys.argv is the list of command-line arguments.
• Len(sys.argv) is the number of command-line arguments.
• Here, sys.argv[0] is the program i.e. script name
import sys
a=int(sys.argv[1])
b=int(sys.argv[2])
c=a+b
print(c)
Output:
import getopt
Python getopt module import sys
args='-a -b -c -foo -d bar a1 a2'.split()
• Python getopt module helps you parse optlist,args=getopt.getopt(args,'abc:d')
command-line options and arguments. print('option list',optlist)
getopt.getopt(args,options,[long_options]) print('Arguments',args)
• Args: This is the argument list to be parsed.
args='-a -b -cfoo -d bar a1 a2'.split()
• Options: This is the string of option letters that the script optlist,args=getopt.getopt(args,'abc:d:')
wants to recognize, with options that require an argument
print('option list',optlist)
should be followed by a colon (:)
print('Arguments',args)
• Long_options: This is optional parameter and if specified,
must be a list of strings with the names of the long
options, which should be supported. Long options, which
require an argument should be followed by an equal
sign(‘=‘). To accept only long_options should be an empty
string
Problems Given
1. Copy from one file to another
2. Word count
3. Longest word
Copy from one file to another
print("Title of the program: Copy of one file to another")
f1=input("Enter the source file to be copied")
f2=input("Enter the destination file")
f1=open(f1,"r")
f2=open(f2,"w")
for i in f1.readlines():
f2.write(i)
f1.close()
f2.close()
Output
==============================
=== RESTART:
C:\Users\abikasi\Desktop\lg.py
==============================
===
Title of the program: Copy of one file
to another
Enter the source file to be copied
sample.txt
Enter the destination filefile2.txt
1 file copied
Words Count
f1="file1.txt"
with open(f1,"r") as f:
content=f.read()
print("File1 Content: \n",content)
words=content.split()
word_count = len(words)
print("Total number of words in the file:",word_count)
Output
File1 Content:
Information Technology
Velammal College of Engineering and Technology
Madurai
Total number of words in the file: 9
Longest Word
f1="file1.txt"
with open(f1, "r") as f:
wordsList = f.read().split()
longestWordLength = len(max(wordsList, key=len))
# Here, we are checking all the words whose length is equal to that of the
longest word
result = [text for text in wordsList if len(text) == longestWordLength]
f.close()
Output
File1 Content:
Information Technology
Velammal College of Engineering and Technology
Madurai
finally:
print("Thank you, you have successfully checked the voting eligibility")
Student mark range validation