lines = ["Hello, World!", "Python is great!", "File handling is useful!", "End of file."]
with open("output.txt", "w") as file:
for line in lines:
file.write(line + "\n")
print("Data written to output.txt successfully!")
#source code --> clcoding.com
Code Explanation:
Create a List of Strings:
We define a list lines that contains multiple strings.
Open the File in Write Mode ("w")
The open("output.txt", "w") statement opens the file in write mode.
If the file does not exist, it will be created.
If the file already exists, it will be overwritten.
Writing to the File:
The for loop iterates through the list of strings.
file.write(line + "\n") writes each string to the file and adds a newline (\n) so that each string appears on a new line.
File Closes Automatically:
The with open(...) statement ensures the file automatically closes after writing.
Print Success Message:
print("Data written to output.txt successfully!") confirms that the process is complete.
0 Comments:
Post a Comment