# 示例代码:Python 文件写入
# 打开一个文件,使用 'w' 模式表示写入模式。如果文件不存在,则会创建新文件;如果文件已存在,则会覆盖原有内容。
with open('example.txt', 'w') as file:
# 写入单行文本
file.write("Hello, World!\n")
# 写入多行文本,使用 writelines 方法
lines = ["This is the first line.\n", "This is the second line.\n"]
file.writelines(lines)
# 使用 'a' 模式追加内容到文件末尾,不会覆盖原有内容
with open('example.txt', 'a') as file:
file.write("This line is appended to the end of the file.\n")
# 读取文件内容以验证写入是否成功
with open('example.txt', 'r') as file:
content = file.read()
print(content)
open()
函数打开文件,'w'
表示写入模式,'a'
表示追加模式。write()
方法写入单行文本,\n
表示换行符。writelines()
方法写入多行文本,传入一个包含多行字符串的列表。'a'
模式打开文件,可以将新内容追加到文件末尾,而不会覆盖原有内容。'r'
模式读取文件内容,以验证写入是否成功。希望这段代码和解释对你有帮助!
上一篇:python中断程序运行
下一篇:python判断字符串不为空
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站