You are on page 1of 20

File Handling

Python 3.6.5
How to open a file?
Python has a built-in function open() to open a file. This
function returns a file object, also called a handle, as it is
used to read or modify the file accordingly.
Modes for Opening of Files
Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new file if it does not exist or truncates the file if it
'w' exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

Open for appending at the end of the file without truncating it. Creates a new file if
'a' it does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)


Opening and closing a file
Safer Way
How to write to File Using Python?
How to read files in Python?
Seek and tell
Read line by line from file
Another way for line by line
Read Lines
Python Directory and Files
Management
• Get Current Directory

• Changing Directory
List Directories and Files
• List current directory

• List specific directory


Making a New Directory
Renaming a Directory or a File
Removing Directory or File
Command line argument
• Write a python script named mycontact.py
import sys
print(“Name : “, sys.argv[1])
print(“Contact No.: “, sys.argv[2])

• Run python script from command line with arguments


C:\work>mycontact rajeev 8115260090
CBSE-X Result Analysis
Creating CSV file
with open("test.csv","w") as f:
f.write("Roll No., Name, Marks\n")
f.write("1,Vinit,30\n")
f.write("2,Alka,26\n")
f.write("3,Rohit,28\n")
Thanks

You might also like