Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. File Handling
  5. File Handling in Python

File Handling in Python

File handling is a crucial aspect of programming, allowing you to interact with files on your computer. It allows developers to create, open, read, write, append, close, and delete files efficiently.

  • In Python, file handling is straightforward and comes with a variety of built-in functions and modules to make the process efficient.
  • File handling in Python allows us to work with files for reading, writing, appending, and managing data. Python provides built-in functions to handle files easily.

Basic File Handling Operations in Python:

Python provides an easy way to work with files using the built-in open() function. Here are the core operations:

  • Creating new files
  • Opening existing files
  • Reading from files
  • Writing to files
  • Closing files
  • Deleting files

Python provides built-in functions and modules to perform these operations, making it easy to work with files.

1.) Creating a New File

# Creating a new file
file = open("newfile.txt", "w")  
file.write("This is a new file.")  
file.close()

print("File created successfully!")

2.) Opening existing files

# Opening an existing file in read mode
file = open("newfile.txt", "r")  
print("File opened successfully!")
file.close()

3.) Reading from files

# Reading content from a file
file = open("newfile.txt", "r")  
content = file.read()  
print("File Content:\n", content)  
file.close()

4.) Writing to files

# Writing data to a file
file = open("newfile.txt", "w")  
file.write("This file has been updated with new content.")  
file.close()

print("File written successfully!")

5.) Closing a File

# Properly closing a file
file = open("newfile.txt", "r")  
print(file.read())  
file.close()

print("File closed successfully!")

6.) Deleting a File

import os

# Deleting a file
if os.path.exists("newfile.txt"):
    os.remove("newfile.txt")
    print("File deleted successfully!")
else:
    print("File does not exist.")
  • Data Storage: Allows saving data permanently for future use.
  • Data Sharing: Facilitates data exchange between programs or users.
  • Data Processing: Enables reading, writing, and modifying large datasets efficiently.
  • Automation: Used in logging systems, configuration files, and automation scripts.

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *