文件的操作

打开文件

file = open("myfile.txt", "r")

  • “r”: 只读模式(默认)。如果文件不存在,将抛出一个错误。
  • “w”: 写入模式。如果文件不存在,将创建一个新文件;如果文件已存在,将截断(即清空)文件。
  • “a”: 追加模式。如果文件不存在,将创建一个新文件;如果文件已存在,将在文件末尾添加内容。
  • “b”: 二进制模式。用于处理二进制文件,例如图片、视频等。
  • “t”: 文本模式(默认)。用于处理文本文件。
模式作用文件不存在原有内容文件指针
r只读❌报错保留文件开头
w只写✅新建直接清空文件开头
a只追加✅新建保留文件末尾
r可读可写❌报错保留文件开头
w可读可写✅新建直接清空文件开头
a可读可写✅新建保留文件末尾
  • r+:不会清空,但文件必须存在;写会覆盖(原因:指针在文件开头
  • w+:打开直接清空文件。
  • a+:写永远跑到最后;想要读取,必须seek(0)把指针移回文件开头。

关闭文件

file.close()

可以使用with语句,这样在代码块结束后会自动关闭文件,无需显式调用close()方法:

with open("myfile.txt", "r") as file: # 执行文件操作,代码块结束后文件会自动关闭 # ...

读取文件内容

with open("myfile.txt", "r") as file: content = file.read() print(content)
with open("myfile.txt", "r") as file: line = file.readline() #逐行读取文件内容 while line: print(line) line = file.readline()
with open("my.txt","r") as file: lines=file.readlines() # 将整个文件内容一次性读取到内存中,并将其作为一个列表返回 for line in lines: print(line)
with open("my.txt", "r") as file: text = file.read(10) #从文件开头读取指定大小的字节的文件内容 print(text)

移动文件指针

file.seek(offset, whence)

offset表示要移动的字节数(正数表示向后移动,负数表示向前移动),whence表示起始点的位置,可以使用以下值:

  • 0(默认值):从文件开头开始计算偏移量。
  • 1:从当前位置开始计算偏移量。
  • 2:从文件末尾开始计算偏移量。

示例一

with open("myfile.txt", "r") as file: file.seek(10) # 将文件指针定位到第10个字节处 content = file.read() print(content)

示例二

with open("myfile.txt", "r") as file: file.seek(5, 1) # 向后移动5个字节 content = file.read() print(content)

示例三

with open("myfile.txt", "r") as file: file.seek(-5, 2) # 向前移动5个字节(从文件末尾开始) content = file.read() print(content)

写入文件内容

with open("my.txt", "w") as file: file.write("nihao wode shijie\n") # 向文件中写入字符串 number = 1345 file.write(str(number)) #必须以字符串的形式提供数据
with open("my.txt","a+") as file : print("wode shijie nihao",file=file) #向文件中打印内容