0% found this document useful (0 votes)
53 views30 pages

U5L1

Files are used to permanently store related information on a disk. There are two types of files in Python - text files and binary files. Text files can be read and edited by humans, while binary files are computer-readable but not human-readable. To perform operations on a file like reading, writing or modifying, it needs to be opened first using the open() function. The file object returned can then be used to read, write or get metadata of the file using methods like read(), write() and tell(). After completing operations, the file should be closed using the close() method. Files can also be renamed or deleted using os module functions like rename() and remove(). Command line arguments passed during script

Uploaded by

Dharvesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views30 pages

U5L1

Files are used to permanently store related information on a disk. There are two types of files in Python - text files and binary files. Text files can be read and edited by humans, while binary files are computer-readable but not human-readable. To perform operations on a file like reading, writing or modifying, it needs to be opened first using the open() function. The file object returned can then be used to read, write or get metadata of the file using methods like read(), write() and tell(). After completing operations, the file should be closed using the close() method. Files can also be renamed or deleted using os module functions like rename() and remove(). Command line arguments passed during script

Uploaded by

Dharvesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

FILES

Introduction :

• File is a named location on disk to store related information.

• Files are used to store data permanently.

• These files can be used whenever required and may be reopened, modified and copied.

• File can be accessed either by absolute file names or relative file names.
• Absolute File Name: A File name which can specify all the directory names starting from
the root of the tree.

• Example: D:\python\unit5.txt

• Relative File Name: It is relative to current working directory.


• Example:
unit5.txt
Types of Files:
• In python, a file is classified as either Text file or Binary file.

Text File:
• A file can be processed (i.e., read, write, modify) using text editor such as notepad is called
text file.
• Text file are stored in a form that is human readable.
Binary File:
• All other files other than text files are called binary file.
• A binary file is a file stored in binary format.
• A binary file is a computer readable but not human readable.
File operations: -

• In python, a file operation takes place in the following order


• Open the file
• Write or read
• Close the file
open () Function: -

• To read or write a file, it is necessary to open it using Python’s built-in function named
open () function.

fileobject = open(filename [, access mode])


Syntax:

The parameters are explained below:


• filename: Name of the file to access.
• access mode: Indicates how the file will be used (read, write, append)

• Example: f = open(“file1.txt”, “w”)


The list of different file opening modes: -
Modes Description
r Opens a file for reading only.
rb Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w Opens a file for writing only.
wb Opens a file for writing only in binary format.
w+ Opens a file for both writing and reading.
wb+ Opens a file for both writing and reading in binary format.
a Opens a file for appending.
ab Opens a file for appending in binary format.
a+ Opens a file for both appending and reading.
ab+ Opens a file for both appending and reading in binary format.
The file Object Attributes:-

• The file object is used to get various information related to that file.

Attribute Description

file.closed Returns true if the file is closed, otherwise false.

file.mode Returns the file access mode with which file was opened.
file.name Returns name of the file.
Example: -

fileobj = open("file1.txt", "w+")


print("Name of the file: ",fileobj.name)
print("Closed or not: ",fileobj.closed)
print("Opening mode: ",fileobj.mode)

Output:-
Name of the file: file1.txt
Closed or not: False
Opening mode: w+
 
 
The close () Method: -

• The function close () of a file object flushes any unwritten information and closes the file
object when there is no more writing to be done.

• Syntax: fileobject.close ()

• The program to perform the open and close operations of a file.

fobj = open("file1.txt", "w+")


print("Name of the file:”, fobj.name)
fobj.close ()
Reading and writing Files: -

The write() Method: -

• The write () method is used to write any string to a file which is opened.

Syntax: fileobject.write(string)

Example: -
fobj = open("file1.txt","w+") Output: -
str1="Hello python"
file1.txt
fobj.write(str1)
fobj.close () Hello python
 
 
The read () Method: -

• The file read() function reads the file contents from an open file.

• Syntax: fileobject.read([count])

• The argument passed is the number of bytes to be read from the opened file.

• This method starts reading from the beginning of the file and if the argument count is
missing, then it tries to read as much as possible, till the end of file.
Example:

f = open("file1.txt", "w+")
str1="Python is a programming language"
f.write(str1)
f.close()
f = open("file1.txt", "r+")
str2= f.read (20)
print("The string read is: ",str2)
f.close()
Output: -
The string read is: Python is a programm
 
File Positions: -

• The tell() method gives the current object position within the file.

• The seek(offset [, from]) method modifies the current file position.

• The offset argument specifies the number of bytes to be moved.


Example:

fobj = open("file1.txt", "w+")


str1="Python is a programming language"
fobj.write(str1)
fobj.close()
Output: -
fobj = open("file1.txt", "r+")
str2= fobj.read(20) The string read is: Python is a programm
print("The string read is: ",str2) current file position: 20
Again the string read is: Python is
pos = fobj.tell()
print ("current file position:", pos)  
pos =f.seek (0, 0)  
str3=f.read (10)
print ("Again the string read is:", str3)
f. close ()
Renaming and Deleting Files: -

• Python os module provides methods that enable us to perform file-processing operations


like renaming and deleting a file.

• To use this module, it is necessary to import the module.


The rename() Method: -
• The rename () method takes two arguments, the current filename and the new filename.

• Syntax:
• os. rename (current filename, new filename)
• Example:
• Following is the example to rename an existing file file1.txt:
  import os
os. rename (“file1.txt”, “file2.txt”)
The remove () Method: -
• The remove () method can be used to delete files by supplying the name of the file to be
deleted as the argument.
Syntax:
• os.remove (file name)

Following is the example to delete an existing file file2.txt


 
import os
  os. remove(“file2.txt”)
Format operator: -
• One of the python’s features is string format operator %.
• The format operator % used to format a set of variables enclosed in a tuple.
Syntax: -
• print(“format string” % (tuple with values))
Example: -
• print("My name is %s and weight is %d" %("xyz",55))
Output: -
• My name is xyz and weight is 55
Format: -

Format symbol Conversion


%s string
%c string
%d integer
%i integer
%f float
Example: 1
• x=15
• print (“%d” %x)

Output:
• 15

Example: 2
• print (“%d%d%d” % (1,2))

Output:
• TypeError: not enough arguments for format string
Example:3
• print (“%d” %” hello”)

Output:
• TypeError: %d format: a real number is required, not str
COMMAND LINE ARGUMENTS

• Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our scripts.

• Python like most other languages provides this feature. sys.argv is a list in Python, which
contains the command line arguments passed to the script.

• We can count the number of arguments using len (sys. argv) function.
To use sys. argv, we have to import the sys module.

import sys
print("No. of arguments:",len (sys. argv))
print("Argument List:”, str (sys. argv))

Output: -
No. of arguments: 1
Argument List:
['C:/Users/ManiKandan/AppData/Local/Programs/Python/Python310/12
.py']
Question Time
File
1. _____are used to store data permanently.
s
2. In python, a file is classified as either
Text__________or_________.
Binary
file file
tell(
3. The _________method gives the current object position within the file.
)
remove
4. The ___________method can be used to delete files.
()
sys.arg
5. _____________is a list in Python, which contains the command line arguments passed to
v
the script.
Thank You

You might also like