0% found this document useful (0 votes)
18 views

Module-8 (File Handling)

file handling in python

Uploaded by

Lakhan Mahato
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module-8 (File Handling)

file handling in python

Uploaded by

Lakhan Mahato
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Module-8

Files input/output
Content
• Printing to the Screen
• Reading Keyboard Input
• The input Function
• Opening and Closing Files
• The open Function
• The file Object Attributes
• The close() Method
• Reading and Writing Files
• The write() Method
• The read() Method
File Open

• File handling is an important part of any web application.


• Python has several functions for creating, reading, updating, and
deleting files.
• The key function for working with files in Python is the open()
function.
• The open() function takes two parameters; filename, and mode.
• There are four different methods (modes) for opening a file:
Modes(Methods)
• "r“- Read- Default value. Opens a file for reading, error if the file does
not exist
• "a“- Append - Opens a file for appending, creates the file if it does not
exist.
• "w“- Write- Opens a file for writing, creates the file if it does not exist.
• "x“- Create- Creates the specified file, returns an error if the file exists.
Syntax
• To open a file for reading it is enough to specify the name of the file:
f = open(“test.txt“,”r”)
Open a file
• Assume we have the following file, located in the same folder as
Python:
• test.txt
• Hello! Welcome to test.txt
This file is for testing purposes.
Good Luck!

• To open the file, use the built-in open() function.


• The open() function returns a file object , which has a read() method for
reading the content of the file:
Example:-
f = open("D:\\myfiles\text.txt", "r")
print(f.read())
#Read two lines of the code.

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Loop
#Loop through the file line by line:
f = open(“test.txt", "r")
for x in f:
print(x)
f = open("demofile.txt", "r")
print(f.readline())
f.close()

#Close the file


Delete a File

# To delete a file, you must import the OS module, and run its
#os.remove() function.
#Remove the file “test.txt":
import os
os.remove("demofile.txt")
#To delete an entire folder, use the os.rmdir() method.
import os
os.rmdir(“foldername")
Thank you

You might also like