打开文件
file = open("myfile.txt", "r")gau
- “r”: 只读模式(默认)。如果文件不存在,将抛出一个错误。
- “w”: 写入模式。如果文件不存在,将创建一个新文件;如果文件已存在,将截断(即清空)文件。
- “a”: 追加模式。如果文件不存在,将创建一个新文件;如果文件已存在,将在文件末尾添加内容。
- “b”: 二进制模式。用于处理二进制文件,例如图片、视频等。
- “t”: 文本模式(默认)。用于处理文本文件。
关闭文件
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) #向文件中打印内容