Creating A File Object by Associating With A Physical File.: Mode Description

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 24

File Handling in Python

Opening a File:
Creating a file object by associating with a physical file.
Syntax:

filevariable = open(filename , mode)

Mode Description
“r” Opens a file for reading
“w” Open file for writing, if the file already exists old contents are
destroyed
“a” Opens a file for appending data from the end of the file

“rb” Opens file for reading binary data.


“wb” Opens a file for writing binary data.

1
Opening a File
Example:
input = open (“Scores.txt”,”r”)
# if file exists in the current directory or else provides the absolute path

input = open(r”C:\pybook\Scores.txt”,”r”)
input = open(R”C:\pybook\scores.txt”,”r”)

# “r” or “R” Specifies the raw input string


input =open (“C:\\pybook\\scores.txt”,”r”)

2
Reading a Data
Method Description

read([number, int]):str Returns the specified number of characters from the file, if the
argument is omitted the entire remaining contents are read.
readline() : str Returns the next line of the file as a string

Readlines() :list Returns a list of the remaining lines in the file.

3
Reading a Data
def main():
infile = open(“test.py”,”r”)
# read using read() method
print(infile.read())
infile.close()

#read using read(number)


infile = open(“test.py”,”r”)
s1= infile.read(4)
print (s1)
s2=infile.read(10)
print(s2)
infile.close()

4
Reading data
infile = open (r"C:\Python34\anag1.py","r")
line= infile.readline()
while(line != ""):
#print(line)
for l in line:
print(l)
line=infile.readline()
infile.close()

5
Reading a file
infile = open (r"C:\Python34\anag1.py","r")
line= infile.readline()
while(line != None and len(line) >0):
print(line)
line=infile.readline()
infile.close()

infile = open (r"C:\Python34\anag1.py","r")


for line in infile:
if line != None or line !="":
print(line)
infile.close()

6
Counting characters and line
infile = open (r"C:\Python34\anag1.py","r")
lineCount =0
charCount=0
for line in infile:
if line != None or line !="":
lineCount +=1
charCount +=len(line)
print("The number of lines =",lineCount)
print("the number of characrers =",charCount)
infile.close()

7
Common python functions
# Open a file in write mode
fo = open("foo.txt", "rw+")
# Assuming file has following 5 lines
str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(6):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()

8
File readings using ‘with’
with open(“data.txt”,”r”) as f:
data = f.readlines()
for line in data:
words = line.split()
print (words)

9
File Handling in Python
lPython provides basic functions and methods necessary to manipulate files by
default. You can do your most of the file manipulation using a file object.
lBefore you can read or write a file, you have to open it using Python's built-in open()
function. This function creates a file object which would be utilized to call other
support methods associated with it.
lSyntax:
File Modes
File Modes
Opening a File
lSyntax
l filehandle =open (“file1.txt”,”mode)
l Open function returns a handle to the specific file.
Attributes of File Objects
Reading from file
lThe file class contains the methods for reading and writing to a file. For
reading it provides three methods

read( [number, int]) :str


l Return the specified number of character from the file if the parameter is
omitted it reads the entire contents from the file.

readline( ) :str
l Return the next line of the string from the file.
Readlines () :list
l Return the list containing the lines of the file
Writing to a File
lFor writing python provides write method
lSyntax:
l Write(str);

Example:

file = open("Count.py",'w')
str = input("Enter a String")
while str != "":
file.write(str)
file.write('\n')
str=input("Enter a String")
file.close()
Checking file existence
import os.path
if os.path.isfile("Count.py"):
file = open("Count.py",'r')
str = file.readlines()
for st in str:
print(st)
file.close()
Appending data to a file
import os.path
if os.path.isfile("Count.py"):
file = open("Count.py",'a')
file.write("Appending demo")
file.write('\n')
file.write("Ends here")
file.close()
Reading and Writing numeric Data
import random
file = open("Count.py",'w')
for i in range(10):
file.write(str(random.randint(1,100))+ " ")
file.close()
file =open("Count.py",'r')
str = file.read()
numbers = [eval(x) for x in str.split()]
for number in numbers:
print(number,end=",")
file.close();
File Dialogs
lThe tkinter.filedialog module contains the functions askopenfilename and
asksaveasfilename for displaying the file Open and Save As dialog boxes.

# Display a file dialog box for opening an existing file


filename = askopenfilename()

# Display a file dialog box for specifying a file for saving data
filename = asksaveasfilename()
File Dialog
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename

filenameforReading = askopenfilename()
print("You can read from " + filenameforReading)
filenameforWriting = asksaveasfilename()
print("You can write data to " + filenameforWriting)
def main():
filename = input("Enter a filename: ").strip()
infile = open(filename, "r") # Open the file
counts = 26 * [0] # Create and initialize counts
for line in infile:
for i in range(len(counts)):
if counts[i] != 0:
print(chr(ord('a') + i) + " appears " + str(counts[i]) + (" time" if
counts[i] == 1 else " times"))
infile.close() # Close file
def countLetters(line, counts):
for ch in line:
if :
counts[ord(ch) - ord('a')] += 1
main()
Count the Number of Words in a
Text File
l
fname = input("Enter file name: ")
l
num_words = 0
l
with open(fname, 'r') as f:
l
for line in f:
l
words = line.split()
l
num_words += len(words)
l
print("Number of words:")
l
print(num_words)
Counting Occurrence of each word in a file
l

l
file=open("Count.py","r+")
l
wordcount={}
l
for word in file.read().split():
l
if word not in wordcount:
l
wordcount[word] = 1
l
else:
l
wordcount[word] += 1
l
print (word,wordcount)
l
file.close();

You might also like