Ad Code

File Handling in Python.


 File Handling in Python 

Hy, In this tutorial, we will learn How to create file, how to read a new file and existing file, how to write in a file.



What is a file?

A file is a collection of similar types of records and is a container in a computer system for storing information.

What is File Handling in Python?


File handling in Python enables us to create, update, read, and delete the files stored on the local file system through our Python program.

Operations can be performed on a file.

  • Creating new file
  • Opening new and exist file
  • Read file
  • Write into a file
  • Delete a file

File Opening Mode:

"r" - When reading a file.
"w"- When you want to write in a file.
"a" - Create a new file.

Suppose we have a file "MyFile.txt" and the content of the is "Hy, I am Ashish from CodingFizz.".

Then, Reading File "MyFile.txt" 


Source Code:

 f=open("MyFile.txt","r") 
  print(f.read()) 
Output:

Hy, I am Ashish from CodingFizz.



When we want to create a new file and write somethings in that file after creating.

Source Code:

 #creating a new file
 f=open("NewFile.txt","a")
 #write to a file
 f.write("You are a good boy.")
 f.close()
 #reading from an exist file
 f=open("NewFile.txt","r")
 print(f.read())

Output:

You are a good boy.

If you want to delete an exist text file from your system.
Then, We will import os 

Source Code:

 import os 
 os.remove("NewFile.txt")


Post a Comment

0 Comments

Ad Code