Python 文件操作(三)

文件处理

open() # 两个参数:文件名和模式 四种打开文件模式:
"r" # 读取 默认值。打开文件读取,文件不存在则报错
"a" # 追加 打开追加文件,文件不存在则创建文件
"w" # 写入 打开文件写入,文件不存在则创建文件
"x" # 创建 创建指定文件,文件存在则返回错误
"t" # 文本 默认值。文本模式
"b" # 二进制模式,如图像
f = open("demofile.txt") = f = open("demofile.txt", "rt")

文件打开

demofile.txt
Hello! Welcome to demofile.txt
This file is for testing purpose.
Gook Luck!
# 打开文件 使用内建的open()函数 read()读取文件内容
f = open("demofile.txt", "r")
print(f.read())
print(f.read(5)) # 返回文件中的前五个字符
print(f.readline()) # 返回一行 若读取前两行则调用两次
for x in f:
    print(x) # 遍历文件
f.close() # 关闭文件

文件写入

# "w" 覆盖全部内容
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

# 写入后,打开并读取该文件:
f = open("demofile3.txt", "r")
print(f.read())

文件删除

# 必须导入OS模块,并运行os.remove()函数
# 检查文件是否存在,然后删除它
import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")
# 删除文件夹 但只能删除空文件夹
os.rmdir("myfolder")
CC BY-NC-SA 4.0 Deed | 署名-非商业性使用-相同方式共享
最后更新时间:2025-10-18 17:07:26