File Handling (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

1

File Implementation

Dr. Karthikeyan N, M.E., Ph. D.


Assistant Professor SG-1
Vellore Institute of Technology and Science,
VIT-Chennai
Mob. No. : 9047525658
Email.id: n.Karthikeyan@vit.ac.in
File

❑ Files are named locations on disk to store related information


❑ permanently store data in a non-volatile memory
❑ Open a file to read from exist file and write to file
❑ file operation takes place in the following order:
1. Open a file
2. read or write (perform operation)
3. Close the file

Opening Files in Python


built-in open() function to open a file
Syntax: file_obj=open(“file_name/path”, “mode”)
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python38/README.txt") # specifying full path
Closing Files in Python
close() - Closing a file will free up the resources that were tied with the file
File Mode(s)
Write to an Existing File

❑ "a" - Append - will append to the end of the file


❑ "w" - Write - will overwrite any existing content
Code:
f=open("CSE1.txt","w")
f.write("hi welcome to CSE department")
f.close()
#open and read the file after the writing:
f=open("CSE1.txt","r")
print(f.read())

#open and read the file line by line:


f=open("CSE1.txt","r")
print(f.readline())
f.close()
File object attributes

file.closed- return true if file is closed otherwise false


file.mode-return access mode which file was opened
file.name—return the name of the file
file.softspace- return false if space explicitly with print, otherwise true
Program:
fp=open("welcome.txt","w")
print("Name of the file:",fp.name) o/p:
print("Closed or Not:",fp.closed) Name of the file: welcome.txt
print("Opening Mode:",fp.mode) Closed or Not: False
fp.close()
Opening Mode: w
print("Closed or Not:",fp.closed)
Closed or Not: True
>>>
Working with text files containing strings
Write method inside a loop to store group of strings into a file
Program:
fp=open("new_file.txt","w")
print("Enter your text and end with @ symbol to stop")
ch=input("Enter your character") o/p:
while(ch!='@'): Enter your text and end with @
symbol to stop
if(ch!='@'):
Enter your characterh
fp.write(ch)
Enter your characteri
ch=input("Enter your character")
Enter your character
fp.close()
Enter your characterk
fp1=open("new_file.txt","r")
Enter your charactera
print("File is reading...")
Enter your characterr
print(fp1.read())
Enter your character@
fp1.close()
File is reading...
hi kar
File with w+ and seek methods

Program:
fp=open("new_file2.txt","w+")
string='''hi welcome to School of computer Science engineering
VIT University, Chennai'''
fp.write(string)
print("File is ready to read...")
fp.seek(0,0) #why this line…
#fp.seek(12,0)
print(fp.read())
fp.close()
Knowing whether a file exists or not
OS module has a sub module by the name ‘path’ that contains a method
isfile()
isfile() – used to know about the status of a file
Os.path.isfile()-gives ‘True’ when file already exists else ‘False’
Syntax:
if os.path.isfile(file_name):
f= open(file_name, “r”)
Import the following modules
else:
import os, sys
print(file_name, “ does not exist”)
sys.exit()
Program to count total no of lines and print line by line from a file
for line in file_object:
print(line)
Program to count no of lines, words and character in a text file
import sys, os
name=input(“enter your file name”)
if os.path.isfile(name):
f=open(name, “r”)
i/p:
else:
print(name, “does not exit”) welcome.txt
sys.exit() Problem Solving Python and Programming
cl=cw=cc=0
o/p:
for line in f:
words=line.split() enter your file name welcome.txt
cl=cl+1 no. of lines 1
cw=cw+len(words)
no. of words 5
cc=len(line)
print(“no. of lines”, cl) no. of characters 38
print(“no. of words”,cw) >>>
print(“no. of characters”,cc”)
f.close()
Rename and deleting file
OS module provides methods to rename and delete files
Syntax:
os.rename(current_file_name, new_file_name)
os.remove(file_name) Import the following module
Example: import os
import os
os.rename(“welcome.txt”, “mech.txt”)
os.remove(“mech.txt”)
Command Line Arguments(1/2)
Python provides another method to give input, called command line
arguments
Diff: input() is used to get i/p while script is running where as command line
arg. is used to get i/p before script is running
purpose:
sys.argv #list of arguments
len(sys.argv) #number of command line arguments
Example: o/p:
import sys name of the script
print(“name of the script”, sys.argv[0]) c:/program/Appdata/Python/first.
py
print(“length of the script”, len(sys.argv))
length of the script 1
print(“arguments are”, sys.argv)
arguments are
[‘c:/program/Appdata/Python/fir
st.py’]
Command Line Arguments(2/2)
Variable arguments
args(*) and kwargs(**) are used to get arbitrary no of arguments in a
function
def command(*vals):
print(“values are:”, vals)
print(“type of vals”, type(vals)) o/p:
mul=1 values are: (5,6)
for i in vals:
type of vals: class ‘tuple’>
mul=mul*i
result is: 30
return mul
o/p:
res=command(5,6)
print(“result is:”, res) values are: (2,5,5)
res=command(2,5,5) type of vals: class ‘tuple’>
print(“result is:”, res) result is: 50
Variable arguments-cont.,
args(*) and kwargs(**) are used to get arbitrary no of arguments in a
function
def command(**vals):
print(“values are:”, vals)
print(“type of vals”, type(vals)) o/p:
print(“Name = ”,vals[‘Name’]) values are: {‘Name’: ‘ Karthikeyan N’,
print(“Department = ”,vals[‘dept’]) ‘rollno’ : ‘7228’, ‘dept’ : ‘CSE’}
command(Name=“Karthikeyan N”, type of vals: class ‘dict’>
rollno=“7228”, dept=“CSE”) Name = Karthikeyan N
Department = CSE
Python File - Exercises
1. Write a Python program to count the frequency of words in a file
Refer I_CSE_B.txt file as input file
2. Write a Python program to copy the contents of a file to another file
copy from I_CSE_B.txt to II_CSE_B.txt
3. Write a python program to read the contents from two file and merge into
another file
copy from I_CSE_B.txt to II_CSE_B.txt to III_CSE_B.txt
4. Write a python program to print the vowel letter of I_CSE_B.txt file
Thank You
Q&A

You might also like