with open("example.txt", "w") as file:
file.write("Hello, World!")
print("File created and text written successfully!")
#source code --> clcoding.com
Code Explanation:
Opening the File:
We use open("example.txt", "w") to open a file named example.txt in write mode ("w").
If the file does not exist, Python creates it automatically.
If the file already exists, its contents will be overwritten.
Using with Statement:
with open(...) as file: is used for better file handling.
It ensures that the file is closed automatically after the block is executed.
Writing to the File:
The write() function writes "Hello, World!" into the file.
Print Confirmation:
The message "File created and text written successfully!" confirms the operation.
Expected Output:
File created and text written successfully!
0 Comments:
Post a Comment