📜  python 将字符串保存到文本 - Python (1)

📅  最后修改于: 2023-12-03 15:34:11.354000             🧑  作者: Mango

Python 将字符串保存到文本

在Python中,可以通过将字符串写入文本文件来保存数据。

示例代码
将字符串写入文件
# 打开文件以写入模式('w')
file = open('example.txt', 'w')

# 要写入的字符串
string = 'hello, world!'

# 将字符串写入文件
file.write(string)

# 关闭文件
file.close()
将多行字符串写入文件
# 打开文件以写入模式('w')
file = open('example.txt', 'w')

# 要写入的字符串
string = """hello,
world!"""

# 将字符串写入文件
file.write(string)

# 关闭文件
file.close()
参考资料