Python_File_Handling1[1]
Python_File_Handling1[1]
PYTHON
SUBMITTED BY:
NAVEEN GUPTA
2201920100189
CSE-D
Python File Handling
• Syntax:
• f= open(filename, mode)
example
• print("NAVEEN GUPTA\n2201920100189\n")
• file=open('naveen.txt','w')
• file.write("This is the write command\n")
• file.write("It allows us to write in a particular file")
• file.close()
• print("File naveen.txt edited successfully.\n")
• print("THE FILE CONTAINS:-")
• file = open('naveen.txt', 'r')
• for each in file:
• print(each)
output
Read files function in
python
• There is more than one way to read a file in
Python. Let us see how we can read the content of
a file in read mode.
• Example 1: The open command will open the file
in the read mode and the for loop will print each
line present in the file.
• Syntax: f = open('filename.txt', 'r')
Example
• print("NAVEEN GUPTA\n2201920100189\n")
• print("THE FILE CONTAINS:-")
• with open("naveen.txt","r") as f1:
• print(f1.read())
• read()
output
Appending files function in
python
• rstrip(): This function strips each line of a file off spaces from
the right-hand side. lstrip(): This function strips each line of a
file off spaces from the left-hand side.
• It is designed to provide much cleaner syntax and exception
handling when you are working with code. That explains why
it’s good practice to use them with a statement where
applicable. This is helpful because using this method any
files opened will be closed automatically after one is done,
so auto-cleanup.
• Syntax:
• f = open('filename.txt', ‘w’)
• f.write(new text)
example
• print("NAVEEN GUPTA\n2201920100189\n")
• with open("naveen.txt", 'a') as f:
• f.write("\nthis is the new text")
• print("Text appended to file naveen.txt
successfully.")
• f.close()
• print("THE FILE CONTAINS:-")
• file = open('naveen.txt', 'r')
• for each in file:
• print(each)
output
Deleting files function in
python
• When any large program is created, usually there are small
files that we need to create to store some data that is needed
for the large programs. when our program is completed, so
we need to delete them. In this article, we will see how to
delete the files in Python.
• Methods to delete Python file
• Python Delete File using os.remove
• Delete files in Python using the send2trash module