How to Create and Delete a file in Python?

How to Create and Delete a file in Python?

This recipe helps you Create and Delete a file in Python
In [1]:
## How to Create and Delete a file in Python
def Kickstarter_Example_54():
    print()
    print(format('How to create and Delete a file in Python','*^82'))
    import warnings
    warnings.filterwarnings("ignore")

    import os
    # Create a file if it doesn't already exist
    with open('file.txt', 'xt') as f:
        # Write to the file
        f.write('This is a New File. Just Created!')
        # Close the connection to the file
        f.close()
    # Open The File And Read It
    with open('file.txt', 'rt') as f:
        # Read the data in the file
        data = f.read()
        # Close the connection to the file
        f.close()
    # View The Contents Of The File
    print(data)

    # Delete The File
    os.remove('file.txt')
Kickstarter_Example_54()
********************How to create and Delete a file in Python*********************
This is a New File. Just Created!


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
1 developer from KPMG
1 developer from YASH Technologies
1 developer from Altimetrik
1 developer from LTI
1 developer from ANAC
1 developer from MudraCircle
1 developer from HvH
1 developer from Vodafone