File Handling in Python

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.

Python3
import os

def create_file(filename):
    try:
        with open(filename, 'w') as f:
            f.write('Hello, world!\n')
        print("File " + filename + " created successfully.")
    except IOError:
        print("Error: could not create file " + filename)

def read_file(filename):
    try:
        with open(filename, 'r') as f:
            contents = f.read()
            print(contents)
    except IOError:
        print("Error: could not read file " + filename)

def append_file(filename, text):
    try:
        with open(filename, 'a') as f:
            f.write(text)
        print("Text appended to file " + filename + " successfully.")
    except IOError:
        print("Error: could not append to file " + filename)

def rename_file(filename, new_filename):
    try:
        os.rename(filename, new_filename)
        print("File " + filename + " renamed to " + 
                  new_filename + " successfully.")
    except IOError:
        print("Error: could not rename file " + filename)

def delete_file(filename):
    try:
        os.remove(filename)
        print("File " + filename + " deleted successfully.")
    except IOError:
        print("Error: could not delete file " + filename)


if __name__ == '__main__':
    filename = "example.txt"
    new_filename = "new_example.txt"

    create_file(filename)
    read_file(filename)
    append_file(filename, "This is some additional text.\n")
    read_file(filename)
    rename_file(filename, new_filename)
    read_file(new_filename)
    delete_file(new_filename)

Output:

File example.txt created successfully.
Hello, world!

Text appended to file example.txt successfully.
Hello, world!
This is some additional text.

File example.txt renamed to new_example.txt successfu...

Python Cheat sheet (2024)

Python is one of the most widely-used and popular programming languages, was developed by Guido van Rossum and released first in 1991. Python is a free and open-source language with a very simple and clean syntax which makes it easy for developers to learn Python. It supports object-oriented programming and is most commonly used to perform general-purpose programming. Python is used in several domains like Data Science, Machine Learning, Deep Learning, Artificial Intelligence, Scientific Computing Scripting, Networking, Game Development Web Development, Web Scraping, and various other domains.

Python Cheat Sheet

To give a comprehensive overview of Python programming, we made a Python Cheat Sheet for Python programmers. In this Cheat Sheet of Python, you’ll learn all the basic to advanced topics and concepts of Python, like Python data types, Python for loop, Python slice, python map function, python dictionary, Python File Handling, etc.

Python Cheat sheet

  • What is Python?
  • Python Input
  • Operators in Python
  • Python Comment
  • DataType in Python
  • Python String
  • Conditional Statements
  • Python Functions
  • Python BuildIn Function
  • Python RegEx
  • File Handling in Python
  • Try and Except Statement
  • Python OOPs Concepts
  • Python Modules
  • Python Interview Questions Answers
  • Python Cheat Sheet – FAQs

Similar Reads

What is Python?

Python is one of the most widely-used and popular programming languages, was developed by Guido van Rossum and released first on February 20, 1991. Python is a free and open-source language with a very simple and clean syntax which makes it easy for developers to learn Python. It supports object-oriented programming and is most commonly used to perform general-purpose programming. Python is used in several domains like Data Science, Machine Learning, Deep Learning, Artificial Intelligence, Scientific Computing Scripting, Networking, Game Development Web Development, Web Scraping, and various other domains....

Python Input

The input() method in Python is used to accept user input. By default, it returns the user input as a string. By default, the input() function accepts user input as a string....

Operators in Python

In general, Operators are used to execute operations on values and variables. These are standard symbols used in logical and mathematical processes....

Python Comment

Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. There are three types of comments in Python:...

DataType in Python

The type() function can be used to define the values of various data types and to check their data types....

Python String

In Python, a string is a data structure that represents a collection of characters. A string cannot be changed once it has been formed because it is an immutable data type....

Conditional Statements

Decision-making statements in programming languages decide the direction(Control Flow) of the flow of program execution....

Python Functions

Python Functions are a collection of statements that serve a specific purpose. The idea is to bring together some often or repeatedly performed actions and construct a function so that we can reuse the code included in it rather than writing the same code for different inputs over and over....

Python BuildIn Function

There are numerous built-in methods in Python that make creating code easier. Learn about the built-in functions of Python in this post as we examine their numerous uses and highlight a few of the most popular ones....

Python RegEx

We define a pattern using a regular expression to match email addresses. The pattern r”\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b” is a common pattern for matching email addresses. Using the re.search() function, the pattern is then found in the given text. If a match is found, we use the match object’s group() method to extract and print the matched email. Otherwise, a message indicating that no email was found is displayed....

File Handling in Python

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files....

Try and Except Statement

In Python, Try and except statements are used to catch and manage exceptions. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause....

Python OOPs Concepts

Object-oriented Programming (OOPs) is a programming paradigm in Python that employs objects and classes. It seeks to include real-world entities such as inheritance, polymorphisms, encapsulation, and so on into programming. The primary idea behind OOPs is to join the data and the functions that act on it as a single unit so that no other portion of the code can access it....

Python Modules

A library is a group of modules that collectively address a certain set of requirements or applications. A module is a file (.py file) that includes functions, class defining statements, and variables linked to a certain activity. The term “standard library modules” refers to the pre-installed Python modules....

Python Interview Questions Answers

Python Interview Questions Answers...

Python Cheat Sheet – FAQs

Q. What are the key features of Python?...

Contact Us