Python Error Handling & File Handling

    

 

Python Error Handling & File Handling for Beginners

In this post, you will learn how Python:

  • Handles errors

  • Reads and writes files

  • Uses modules and packages


1. Python Errors & try-except

When something goes wrong, Python shows an error.Common Error Types

  • ValueError

  • TypeError

  • ZeroDivisionError

  • IndexError

  • KeyError

        Full try-except Syntax

try: x = int(input("Enter a number: ")) y = 10 / x except ValueError: print("Please enter numbers only") except ZeroDivisionError: print("Cannot divide by zero") else: print("Result:", y) finally: print("Done")



2.Python File Handling (Read & Write) :Files help you save data

 

                    file = open("data.txt", "w")

    
                Method             Use
                    read()                         Read file
                    readline()                         Read one line
                    readlines()                         Read all lines
                    write()                         Write text
                    writelines()                         Write many lines
                    close()                         Close file
                    seek()                         Move cursor
                    tell()                         Cursor position

        Example:
          

            1. Write to a File                     file = open("data.txt", "w")

                    file.write("Hello Python")

                    file.close()

            2.Read from a File

                    file = open("data.txt", "r")

                    print(file.read())

                    file.close()

            3.Better Way (with)

                with open("data.txt", "a") as file:

                        file.write("\nLearning Python")



3. Python Modules & Packages

                                A module is a file with Python code.A package is a folder of modules.

                                    Module                        Important Methods
                    math            sqrt(), pow(), ceil(), floor()
                    random            randint(), choice(), shuffle()
                    datetime            now(), date()
                    os            getcwd(), mkdir(), remove()

                    Using a Module

                        import math                         print(math.sqrt(16))

                    Create Your Own Module

                                    Create file: my_module.py

                            def greet(name):                                 print("Hello", name)

                       Use it:

                    import my_module                     my_module.greet("Bency")

Now you can:

  • Handle errors

  • Save data in files

  • Reuse code with modules







Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling