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

file handling

Uploaded by

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

file handling

Uploaded by

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

File Handling

• File handling in Python is a powerful and


versatile tool that can be used to perform a
wide range of operations.
• However, it is important to carefully consider
the advantages and disadvantages of file
handling when writing Python programs, to
ensure that the code is secure, reliable, and
performs well
Advantages of File Handling in
Python
• Versatility: File handling in Python allows you to perform a wide
range of operations, such as creating, reading, writing, appending,
renaming, and deleting files.
• Flexibility: File handling in Python is highly flexible, as it allows
you to work with different file types (e.g. text files, binary
files, CSV files, etc.), and to perform different operations on files
(e.g. read, write, append, etc.).
• User–friendly: Python provides a user-friendly interface for file
handling, making it easy to create, read, and manipulate files.
• Cross-platform: Python file-handling functions work across
different platforms (e.g. Windows, Mac, Linux), allowing for
seamless integration and compatibility.
Disadvantages of File Handling in
Python
• Error-prone: File handling operations in Python can be prone to
errors, especially if the code is not carefully written or if there are
issues with the file system (e.g. file permissions, file locks, etc.).
• Security risks: File handling in Python can also pose security
risks, especially if the program accepts user input that can be used
to access or modify sensitive files on the system.
• Complexity: File handling in Python can be complex, especially
when working with more advanced file formats or operations.
Careful attention must be paid to the code to ensure that files are
handled properly and securely.
• Performance: File handling operations in Python can be slower
than other programming languages, especially when dealing with
large files or performing complex operations.
• Python has several functions for
creating, reading, updating, and
deleting files.
Read Files
• 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 contents of a file.
• The open() function takes 2
parameters filename, and mode
f =open("demofile.txt","r")
print(f.read())

O/P:
Hi this is Python programming
Lets Learn Python.
f=open("file.txt",'r')
print(f.read())
O/p:
FileNotFoundError: [Errno 2] No such file or
directory: 'file.txt'
Read Lines
• We can return one line by using the readline() method.
• f = open("demofile.txt", "r")
print(f.readline())
O/P:Hi this is Python programming

• By looping through the lines of the file, you can read the whole file,
line by line
• f = open("demofile.txt", "r")
for x in f:
print(x)

O/P:
Hi this is Python programming

Lets Learn Python.


Close File
• It is a good practice to always close
the file when you are done with it.
• f = open("demofile.txt", "r")
print(f.readline())
f.close()
• Note: We should always close our
files, in some cases, due to buffering,
changes made to a file may not show
until you close the file.
Python File Write
• To write to an existing file, you must
add a parameter to the open()
function.
• f = open("demofile.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile.txt", "r")
print(f.read())
O/P:
• Hi this is Python programming
• Lets Learn Python.Now the file has more
content!
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the
content!")
f.close()

#open and read the file after the


overwriting:
f = open("demofile.txt", "r")
print(f.read())
Woops! I have deleted the content!
Create a New File
• To create a new file in Python, use
the open() function with one of the
following parameters.
• Create a file called "myfile.txt":
f = open("myfile.txt", "x")

Result: a new empty file is created!


Delete a File
• To delete a file, you must import the
OS module, and run its os.remove()
function.
• import os
os.remove("demofile.txt")
Check if File exist:

• To avoid getting an error, you might


want to check if the file exists before
you try to delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Renaming a file
import os
os.rename('C:/Users/ASUS/Desktop/jupyter
projects/hi.txt', 'C:/Users/ASUS/Desktop/jupyter
projects/bye.txt'
Insertion in a text file
f=open("demofile.txt","r")
lines = f.readlines()
print(lines)
lines.insert(1, "Hi this is new
txt")
f=open("File1.txt","w")
f.writelines(lines)

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