open()文件和内建函数,python2中open()代替了file()

【open()】

file_obj = open(file_path, mode='r', encoding=None, ...)

file_path: 文件路径(相对或绝对路径)。
mode: 文件打开模式(见下文)。
encoding: 文件编码(如 'utf-8',默认取决于系统)。

模式 说明
'r' 只读(默认)
'w' 写入(覆盖原有内容)
'a' 追加(在文件末尾写入)
'x' 创建新文件并写入(文件已存在则报错)
'b' 二进制模式(如 'rb', 'wb')
'+' 读写模式(如 'r+', 'w+')

读取整个文件

with open('example.txt', 'r', encoding='utf-8') as f:
    content = f.read()  # 读取全部内容
print(content)

with open('example.txt', 'r') as f:
    for line in f:  # 逐行读取(推荐)
        print(line.strip())  # 去掉换行符
with open('image.png', 'rb') as f:
    data = f.read()  # 读取二进制数据

写入内容

with open('output.txt', 'w') as f:
    f.write('Hello, World!\n')
    f.writelines(['Line 1\n', 'Line 2\n'])

追加内容

with open('output.txt', 'a') as f:
    f.write('New line appended.\n')
posted @ 2025-06-02 17:52  呆呆酱  阅读(32)  评论(0)    收藏  举报