# 打开文件并读取内容的示例代码
# 使用 open 函数打开一个文件,模式为只读 ('r')
with open('example.txt', 'r') as file:
    # 读取文件的所有内容
    content = file.read()
    print(content)
# 使用 open 函数打开一个文件,模式为写入 ('w'),如果文件存在则会被清空
with open('output.txt', 'w') as file:
    # 写入一些文本到文件中
    file.write('Hello, World!')
# 使用 open 函数打开一个文件,模式为追加 ('a'),在文件末尾添加内容
with open('log.txt', 'a') as file:
    # 追加一行日志到文件中
    file.write('An error occurred.\n')
# 使用 open 函数打开一个文件,模式为读取二进制文件 ('rb')
with open('image.png', 'rb') as file:
    # 读取二进制文件的内容
    binary_data = file.read()
    print(binary_data)open() 函数用于打开文件,并返回一个文件对象。'r', 'w', 'a', 'rb' 等) 指定了文件的打开方式:'r':只读模式(默认),文件必须存在。'w':写入模式,如果文件存在则会被清空,如果不存在则创建新文件。'a':追加模式,在文件末尾添加内容,如果文件不存在则创建新文件。'rb':读取二进制文件。with 语句确保文件在使用完毕后自动关闭,避免资源泄漏。上一篇:python程序运行
下一篇:python pipeline
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站