Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

open函数python

作者:看破了搪塞   发布日期:2025-09-07   浏览:39

# 打开文件并读取内容的示例代码

# 使用 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

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站