13 文件操作
13.1 文件介绍
- 什么是文件?
- 文件属于文件的一种,与普通文件载体不同,文件是以硬盘为载体存储在计算机上的信息集合
- 文件可以是文本文档、图片、程序等等。文件通常具有点+三个字母的文件扩展名,用于指示文件类型(例如,图片文件常常以JPEG格式保存并且文件扩展名为.jpg)
- 文件的作用
- 就是把一些内容(数据)存放起来,可以让程序下一次执行的时候直接使用,而不必重新制作一份,省时省力
13.2 文件打开与关闭
- 打开文件
open(name, mode)- name:是要打开的目标文件名的字符串(可以包含文件所在的具体路径)
- mode:设置打开文件的模式(访问模式):只读、写入、追加等
f = open('test.txt', 'w')
关闭文件
close()# 新建一个文件,文件名为:test.txt f = open('test.txt', 'w') # 关闭这个文件 f.close()
| 模式 | 描述 |
|---|---|
| r | 以只读方式打开文件,文件的指针将会放在文件的开头,这是默认模式 |
| rb | 以二进制格式打开一个文件用于只读,文件指针将会放在文件的开头,这是默认模式 |
| r+ | 打开一个文件用于读写,文件指针将会放在文件的开头 |
| rb+ | 以二进制格式打开一个文件用于读写,文件指针将会放在文件的开头 |
| w | 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件 |
| wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件 |
| w+ | 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件 |
| wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件 |
| a | 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入 |
| ab | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入 |
| a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写 |
| ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写 |
13.3 文件读写
13.3.1 写数据
- 使用
write()可以完成向文件写入数据
- 新建一个文件 file_write_test.py,向其中写入如下代码:
f = open('test.txt', 'w') f.write('hello world, i am here!') f.close() - 运行之后会在 file_write_test.py 文件所在的路径中创建一个文件test.txt,并写入上述内容
- 注意:
- w 和 a 模式:如果文件不存在则创建该文件;如果文件存在,w 模式先清空再写入,a 模式直接末尾追加
- r 模式:如果文件不存在则报错
13.3.2 读数据
read(num):使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
f = open('test.txt', 'r') content = f.read(5) # 最多读取5个数据 print(content) print("-"*30) # 分割线,用来测试 content = f.read() # 从上次读取的位置继续读取剩下的所有的数据 print(content) f.close() # 关闭文件,这个可以是个好习惯哦hello ------------------------------ world, i am here!- 如果用 open 打开文件时,如果使用的 "r" ,那么可以省略,即只写 open('test.txt')
readlines():就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素
f = open('test.txt', 'w') for i in range(5): f.write('hello world, i am here!') f.write('\n') f = open('test.txt', 'r') content = f.readlines() print(type(content)) print(content) i = 1 for temp in content: print("%d:%s" % (i, temp)) i += 1 f.close()<class 'list'> ['hello world, i am here!\n', 'hello world, i am here!\n', 'hello world, i am here!\n', 'hello world, i am here!\n', 'hello world, i am here!\n'] 1:hello world, i am here! 2:hello world, i am here! 3:hello world, i am here! 4:hello world, i am here! 5:hello world, i am here!
readlines():就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素
f = open('test.txt', 'w') for i in range(5): f.write('hello world, i am here!') f.write('\n') f = open('test.txt', 'r') content = f.readlines() print(type(content)) print(content) i = 1 for temp in content: print("%d:%s" % (i, temp)) i += 1 f.close()<class 'list'> ['hello world, i am here!\n', 'hello world, i am here!\n', 'hello world, i am here!\n', 'hello world, i am here!\n', 'hello world, i am here!\n'] 1:hello world, i am here! 2:hello world, i am here! 3:hello world, i am here! 4:hello world, i am here! 5:hello world, i am here!
readline():一次读取一行内容
f = open('test.txt', 'r') content = f.readline() print("1:%s" % content) content = f.readline() print("2:%s" % content) f.close()1:hello world, i am here! 2:hello world, i am here!
13.4 文件定位读写
13.4.1 获取当前读写的位置
在读写文件的过程中,如果想知道当前的位置,可以使用tell()来获取
# 打开一个已经存在的文件 f = open('test.txt', 'r') str = f.read(3) print("读取的数据是 :%s " % str) # 查找当前位置 position = f.tell() print("当前文件位置 :%d " % position) str = f.read(3) print("读取的数据是 :%s " % str) # 查找当前位置 position = f.tell() print("当前文件位置 : %d" % position) f.close()读取的数据是 :hel 当前文件位置 :3 读取的数据是 :lo 当前文件位置 : 6
13.4.2 定位到某个位置
- 如果在读写文件的过程中,需要从另外一个位置进行操作的话,可以使用seek()
- seek(offset, from)有2个参数
- offset:偏移量
- from:方向
- 0:表示文件开头
- 1:表示当前位置
- 2:表示文件末尾
把位置设置为:从文件开头,偏移5个字节
# 打开一个已经存在的文件 f = open("test.txt", "r") str = f.read(10) print("读取的数据是 :%s " % str) # 查找当前位置 position = f.tell() print("当前文件位置 :%d" % position) # 重新设置位置 f.seek(5,0) # 查找当前位置 position = f.tell() print("当前文件位置 :%d " % position) str = f.read(3) print("读取的数据是 :%s " % str) f.close()读取的数据是 :hello worl 当前文件位置 :10 当前文件位置 :5 读取的数据是 : wo
把位置设置为:离文件末尾,3字节处
# 在文本文件中,没有使用b模式选项打开的文件,只允许从文件头开始计算相对位置,从文件尾计算时就会引发异常 f = open("test.txt", "rb") str = f.read(10) print("读取的数据是 :%s " % str) # 查找当前位置 position = f.tell() print("当前文件位置 :%d" % position) # 重新设置位置 f.seek(-3, 2) # 查找当前位置 position = f.tell() print("当前文件位置 :%d " % position) str = f.read(3) print("读取的数据是 :%s " % str) f.close()读取的数据是 :'hello worl' 当前文件位置 :10 当前文件位置 :120 读取的数据是 :'re!'
13.5 文件操作
13.5.1 文件重命名
- os模块中的
rename()可以完成对文件的重命名操作
- rename(需要修改的文件名, 新的文件名)
import os os.rename("毕业论文.txt", "毕业论文-最终版.txt")
13.5.2 删除文件
- remove(待删除的文件名)
import os os.remove("毕业论文.txt")
13.5.3 创建文件夹
- mkdir(文件夹名称)
import os os.mkdir("张三")
13.5.4 获取当前目录
- getcwd()
import os os.getcwd()
13.5.5 改变默认目录
- chdir("../")
import os os.chdir("../")
13.5.6 获取目录列表
- listdir("./")
import os os.listdir("./")
13.5.7 删除文件夹
- os.rmdir(要删除的文件夹名称)
import os os.rmdir("张三")
13.6 综合应用
13.6.1 制作文件的备份
输入文件的名字,然后程序自动完成对文件进行备份
# 提示输入文件 oldFileName = input("请输入要拷贝的文件名字:") # 以读的方式打开文件 oldFile = open(oldFileName,'rb') # 提取文件的后缀 fileFlagNum = oldFileName.rfind('.') if fileFlagNum > 0: fileFlag = oldFileName[fileFlagNum:] # 组织新的文件名字 newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag # 创建新文件 newFile = open(newFileName, 'wb') # 把旧文件中的数据,一行一行的进行复制到新文件中 for lineContent in oldFile.readlines(): newFile.write(lineContent) # 关闭文件 oldFile.close() newFile.close()
13.6.2 批量修改文件名
批量修改文件名,既可添加指定字符串,又能删除指定字符串
# 批量在文件名前加前缀 import os funFlag = 1 # 1表示添加标志 2表示删除标志 folderName = './renameDir/' # 获取指定路径的所有文件名字 dirList = os.listdir(folderName) # 遍历输出所有文件名字 for name in dirList: print name if funFlag == 1: newName = '[Python]-' + name elif funFlag == 2: num = len('[Python]-') newName = name[num:] print newName os.rename(folderName+name, folderName+newName)