在Python中,保存字符串到txt文件非常简单。你可以使用内置的open()
函数来打开一个文件,并指定模式为'w'
(写入模式)或'a'
(追加模式)。然后,你可以使用write()
方法将字符串写入文件。
下面是一个示例,演示如何将字符串保存到txt文件:
# 字符串
my_string = "Hello, world! This is a string to be saved in a txt file."
# 打开文件(如果文件不存在,则创建它)
# 使用 'w' 模式会覆盖文件中的任何现有内容
# 使用 'a' 模式会将内容追加到文件的末尾
with open('output.txt', 'w'