File Handling

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy