Python string variable content or string data can be written into the text file using different methods. A string is a value that is interpreted as characters event numbers like 1,3,5 are interpreted as text.
Write String To Text File with write() Method
The write() method can be used to write a string into a text file. First, the file should be opened with the open() method. The string we want to write provided to the write() method as a parameter. The last step is closing the file to save changes.
text_file = open("text.txt", "w")
text_file.write("I like pythontect.com")
text_file.close()
Alternatively, the string can be written into a text file by using the context manager. By using content manager the string writes operation is more reliable. In this case, there is no need to close the file explicitly because the context manager closes the file implicitly.
with open("text.txt", "w") as text_file:
text_file.write("I like pythontect.com")
Write String Variable To Text File with write() Method
The string can be stored in a string variable and the content of the string variable can be written into a text file by using the write method.
text_file = open("text.txt", "w")
name="pythontect.com"
text_file.write("I like %s",name)
text_file.close()
Write Formatted String To Text File with write() Method
The string can be also written into a text file by formatting. The format() method of the string type can be used to format.
text_file = open("text.txt", "w")
name="pythontect.com"
text_file.write("I like {}".format(name))
text_file.close()
Write String To Text File with print() Method
The print method is very useful method which can be also used to print given text into a text file. The print() method accepts the file parameter which is set to the opened file.
text_file = open("text.txt", "w")
name="pythontect.com"
print("I like {}".format(name),file=text_file)
text_file.close()