Print string to text file
In Python, you can use the built-in open() function to create a text file and write a string to it.
In Python, you can use the built-in open() function to create a text file and write a string to it. Here is an example:
Create a text file and write a string to it in Python using the open function
string = "Hello, World!"
with open("example.txt", "w") as file:
file.write(string)This code creates a new text file named "example.txt" in the current directory and writes the string "Hello, World!" to it. The w argument passed to the open() function tells Python to open the file in write mode, which means that any existing content in the file will be truncated and replaced with the new data.
In case you want to append the string to the end of the file, use 'a' instead of 'w'
Append a string to the end of a file in Python
with open("example.txt", "a") as file:
file.write(string)This will append the string to the end of the text file.