Day03,Python文件的常见操作

一、基本操作

1、操作流程

打开文件,得到文件句柄并赋值给一个变量

通过句柄对文件进行操作

关闭文件

2、打开文件的两种方式

使用open方法

open(file, mode, encoding)

打开文件的模式如下:

image

3、r+,w+,a+的区别

# r+打开文件指针在文件开头,写入文件时不管指针在哪里都在文件末尾添加
f = open("song.bak", "r+", encoding="utf-8")
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.write("----------hello--------")
f.close()

# w+文件存在则删除内容,不存在则创建新文件
f1 = open("song.bak", "w+", encoding="utf-8")
print(f1.readline())
print(f1.readline())
print(f1.readline())
print(f1.tell())
f1.write("----------hello--------")
f1.close()

# a+打开文件指针在文件末尾,写入文件时文件末尾添加
f2 = open("song.bak", "a+", encoding="utf-8")
print(f2.readline())
print(f2.readline())
print(f2.readline())
print(f2.seek(100))
f2.write("----------hello--------")
f2.close()

4、其它方法

f.seek(offset, whence)
offset:打针偏移量
whence:可选,默认值为0。表示从哪个位置开始偏移,0代表文件开头,1代表当前位置,2代表末尾
f.read():读取整个文件内容
f.readline():读取指针的当前行
f.readlines():读取整个文件,返回读取所有行的列表
f.tell():返回当前读取文件的指针位置

5、with...open...

为也避免打开文件后忘记关闭,语法如下:
with open(file, mode) as f:
    …
with支持同时对多个文件管理:
with open(file1, mode) as f1, open(file2, mode) as f2:
    …

二、文件的其他操作

1、os模块的常见操作

os.rename(filename, new_filename):文件重命名
os.remove(filename):删除文件
os.mkdir(“dirname/filepath”):创建文件夹
os.getcwd():获取当前目录
os.chdir(“filepath”):改变默认目录
os.listdir(“filepath”):获取目录列表
os.rmdir(“filepath”):删除文件夹

猜你喜欢

转载自blog.51cto.com/zouqq/2326251