Python基础系列九:文件操作

1. 文本文件和二进制文件

按文件中数据组织形式,文件可以分为文本文件和二进制文件
文本文件:存储的字符文本,Python中默认unicode字符集(两个字节表示一个字符,共65536个字符),可以用记事本打开。
二进制文件: 存储的字节文件,不能用记事本打开,常见的二进制文件有mp4视频,jpg图片,doc文档等。

2. 创建文件对象open()

open()函数用于创建对象,创建格式如下

						open(文件名[,打开方式])

文件的打开方式有一下几种,默认创建的是文本文件

模式描述
r读模式
w写模式。如果文件不存在则创建;文件存在则重写
a写模式。如果文件不存在则创建;文件存在则覆盖
b二进制模式(可与其他模式组合使用)
+读写模式(可与其他模式组合使用)

文件的写入有三个步骤

  1. 创建文件对象
  2. 写入数据
  3. 关闭文件对象

3. 编码问题

3.1 常见编码介绍

python程序通常使用unicode编码,文件存储通常使用utf-8,常见编码之间的关系如下,GB编码跟UTF-8不兼容会造成乱码。

3.2 中文乱码问题

windows操作系统默认的编码是GBK,Linux操作系统默认的编码是UTF-8,Python程序默认使用的是Unicode。当我们使用open()时,调用的是操作系统打开的文件,默认的编码是GBK。

4. write/writelines写操作

write写入字符
writelines写入字符串列表,不添加换行

f=open("a.txt","w","encoding=utf-8")
s = ["hello,how are you","my name is lilei","i am 20 years old"]
f.writelines(s)
f.close()

5. with上下文管理器

with可以管理上下文资源, 不论何种原因跳出with,都能确保文件的正确关闭,并且在代码执行完毕后自动还原进入该代码块时的现场。

s = ["hello,how are you","my name is lilei","i am 20 years old"]
with open("a.txt","w",encoding="utf-8") as f:
	f.writelines(s) #写入后回到open之前的现场.

6. 文件读操作

6.1 read([size])

从文件中读取size,并作为结果返回。如果没有size,则读取整个文件,读取到结尾后返回空 字符串

with open(r"a.txt","r",encoding="utf-8") as f:
	print(f.read()) 
	print(f.read(5))

6.2 readline()

读取一行内容作为结果返回。读取到文件末尾,会返回空字符串。

6.3 readlines()

文本文件中,每一行作为一个字符串存入列表中,返回该列表。

7. enumerate()函数

enumerate():推导式生成列表

with open("a.txt","r",encoding="utf-8") as f:
    lines = f.readlines()
    lines = [line.rstrip()+"#"+str(index+1)+"\n" for index,line in enumerate(lines)]

with open("b.txt","w",encoding="utf-8") as f:
    f.writelines(lines)

8. 二进制文件的读写

with open("a.png","rb") as f:
    lines = f.readlines()
    with open("b.png", "wb") as w:
        for line in lines:
            w.write(line)

9. seek()函数

seek(offset,[whence]):把文件指针移动到新的位置,offset表示相对于whence的多少个字节的偏移量
offset:为正表示往结束方向移动,为负表示往开始方向移动
whence不同的值代表的含义如下:

whence值含义
0从文件头开始计算(默认值)
1从当前位置开始计算
2从文件尾开始计算
with open("a.txt","r",encoding="utf-8") as f:
    print(f.readline())
    print(f.tell())
    f.seek(3)
    print(f.readline())

10. csv文件的读取和写入

csv(Comma Separated Values)是逗号分隔符文本格式,常用于数据交换、Excel文件和数据库数据的导入和导出。与Excel文件不同,csv文件有以下几个特点:

  1. 值没有类型,所有值都是字符串
  2. 不能指定字体颜色等样式
  3. 不能指定单元格的宽高,不能合并单元格
  4. 没有多个工作表
  5. 不能嵌入图像图表

10.1 csv.reader读取文件

import csv
with open("test.csv","r") as f:
    a_csv = csv.reader(f)
    print(list(a_csv))
    for row in a_csv:
        print(row)

10.2 csv.write写文件

import csv
with open("test_copy.csv","w") as f:
    w_csv = csv.writer(f)
    w_csv.writerow(["name","age","job"])
    w_csv.writerow(["lily","22","doctor"])
    data = [["lucy","20","student"],["mike","30","teacher"]]
    w_csv.writerows(data)
    with open("test.csv","r") as r:
        a_csv = csv.reader(r)
        w_csv.writerows(a_csv)

11. os模块

os模块可以帮助我们直接对操作系统进行操作,可以直接调用操作系统的可执行文件、命令、直接操作文件、目录等。
os.system可以帮助我们直接调用系统的命令

import os
os.system("notepad.exe")
os.system("ping www.baidu.com")

11.1 os-文件和目录操作

获取文件和文件夹相关的信息

  1. os.name:操作系统信息
  2. os.sep:系统分隔符
  3. os.linesep:换行符
  4. os.stat(文件/文件夹):列举文件和文件夹的所有信息

关于工作目录的操作

  1. os.getcwd():获取当前工作目录
  2. os.mkdir():创建新目录

创建目录、创建多级目录、删除

  1. os.chdir():改变工作路径
  2. os.rmdir():删除目录
  3. os.mkdirs():创建多级目录
  4. os.removedirs():删除多级目录,仅限删除空目录
  5. os.rename(src,dest):文件重命名
  6. os.listdir():返回目录下的所有子文件

11.2 os.path模块

os.path模块提供了目录相关(路径判断、路径切分、路径链接、文件夹遍历)的操作

import os
import os.path

print(os.path.isabs("d:/a.txt")) #是否绝对路径
print(os.path.isdir("d:/a.txt")) #是否目录
print(os.path.isfile("d:/a.txt")) #是否文件
print(os.path.exists("d:/a.txt")) #文件是否存在

print(os.path.getsize("b.txt")) #获取文件大小
print(os.path.abspath("b.txt")) #获取绝对路径
print(os.path.dirname("d:/a.txt")) #获取路径位置

print(os.path.getctime("b.txt")) #获取文件创建时间
print(os.path.getatime("b.txt")) #获取文件访问时间
print(os.path.getmtime("b.txt")) #获取文件修改时间

####对路径的操作#######
path = os.path.abspath("b.txt")
print(os.path.split(path))
print(os.path.splittext(path)) #按.分割,将文件和后缀分割
print(os.path.join("aa","bb","cc"))

11.3 os.walk遍历所有文件和目录

os.walk返回三个值:dirpath,dirnames,filenames

all_file = []
path = os.getcwd()
list_files = os.walk(path)

for dirpath,dirnames,filenames in list_files:
    for dir in dirnames:
        all_file.append(os.path.join(dirpath,dir))
    for file in filenames:
        all_file.append(os.path.join(dirpath,file))
        
for file in all_file:
    print(file)

12. shutil和zip模块(拷贝和压缩)

shutil模块时python标准库中提供的,主要用来做文件和文件夹的拷贝、移动、删除等,还可以做文件和文件夹的压缩、解压缩操作。

import shutil
import zipfile
shutil.copyfile("test.txt","test_copy.txt") #文件拷贝
shutil.copytree("movie/2012","film") #文件夹拷贝
#文件夹拷贝,忽略后缀.txt和.html的文件
shutil.copytree("movie/2012","film",ignore=shutil.ignore_patterns("*.txt","*.html")) 

shutil.make_archive("movie_2012","zip","movie/2012") #压缩
z1 = zipfile.ZipFile("d:/a.zip","w")
z1.write("1.txt")
z1.write("1_copy.txt")
z1.close()

z2 = zipfile.ZipFile("d:/a.zip","r")
z2.extractall("movie")
z2.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值