Python 写入多行字符串到文件
要将多行字符串写入 Python 文件,可以使用文件对象的 write 方法将字符串写入文件中。以下是一个示例:
# 打开文件,使用 'w' 模式以覆盖原有内容
with open('myfile.py', 'w') as f:
# 多行字符串
content = '''
def hello():
print('Hello, world!')
hello()
'''
# 将多行字符串写入文件
f.write(content)
运行后,将在当前目录下创建一个名为 myfile.py 的文件,并将多行字符串写入其中。
原文地址: https://www.cveoy.top/t/topic/o80V 著作权归作者所有。请勿转载和采集!