Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, April 16, 2024

Write a program to create a file in write mode and add some contents into it and display the output.

Code:

def main():

    # Open a file in write mode

    file_path = "output.txt"

    with open(file_path, "w") as file:

        # Write some content to the file

        file.write("Hello, this is some content written to the file.\n")

        file.write("Adding more lines for demonstration.\n")

        file.write("Python is a powerful language for file handling.\n")


    # Read and display the contents of the file

    with open(file_path, "r") as file:

        contents = file.read()

        print("Contents of the file:")

        print(contents)


# Call the main function directly

main()


Output:




No comments:

Post a Comment