1. 文件的读取形式
1.文本形式
r | 以文本打开文件,存在打开成功,不存在失败 |
---|---|
w | 不管文件是否存在都会创建一个新的文件 |
a | 打开文件追加,文件不存在,创建文件,文件存在,在最后边进行追加 |
2.二进制的读取
rb | 二进制读取 |
---|---|
wb | 二进制写入 |
ab | 二进制追加 |
r + w+ a+ 都有写入的权限
2.文件的读取read()和写入write()
open文件以后操作完成必须close
案例:
file = open('a.txt','rt')
print(file)
file.close()
read() | 可以定义要读取的字节,一般4096 |
---|---|
readline() | 只读取一行 |
readlines() | 读取全部,但是按照行的模式读取 |
file = open('a.txt','rt')
# content = file.read()
# 指定读取一部分
# content = file.read(6)
# print(content)
# 读取多行
while True:
# 4096 代表4096个字节
content = file.read(4096)
# 如果读取的文件内容为空就结束读取文件
if content == '':
break
print(content,end='')
file.close()
# 其他方式的读取
file1 = open('a.txt','rt')
# 1行读取,
# con = file1.readline()
# 按照行的形式读取整个文件
con = file1.readlines()
for v in con:
print(v)
print(v.upper())
# print(con)
file1.close()
写入:
s = 'hello'
file = open('a.txt','w')
file.write(s)
file.close()
3. os模块的一些操作
首先要导入os模块才能进行操作
rename() | 重命名文件 |
---|---|
remove() | 删除文件 |
mkdir() | 创建一个文件夹,已存在会报错 |
getcwd() | 获取当前的工作目录 |
chdir() | 改变当前工作目录 |
listdir() | 查看当前目录下的所有文件名称,list |
rmdir() | 删除文件夹,非空不能删除 |
案例:
import os
# 重命名
os.rename('a.txt','b.txt')
# 创建目录 目录存在就会报错
os.mkdir('test_dir')
# 获取当前的工作目录
cwd = os.getcwd()
print(cwd)
# 获取当前的目录下的文件列表
l1 = os.listdir('.')
print(l1)
for c in l1:
print(c)
# 改变当前的目录
os.chdir('D:\pycharmwork\day01')
# 删除一个文件
os.remove('b.txt')
# 删除一个文件夹,目录不为空不能删除
os.rmdir('test_dir')
4. 练习
4.1 复制一个文件
思路:
1.源文件与目标文件
2.怎么结束读取,读取的内容为空,文本文件为空’’,二进制文件为空要加上b,b’’
3.文件完成以后要关闭
def copy_file(src,dest):
file1 = open(src,'r')
file2 = open(dest,'w')
while True:
con = file1.read(1024)
if con =='':
print('copy ok!!')
break
file2.write(con)
file1.close()
file2.close()
copy_file('b.txt','b_bak.txt')
4.2 批量的读取文件改名之后复制
'''
改名以后批量复制
'''
import os
import shutil
def copy_file(src,dest):
# 获取当前的目录
print(os.getcwd())
#切换到源文件的目录中
os.chdir(src)
# 从原目录读取信息
file_list = os.listdir(src)
#创建一个新的目标文件夹
if os.path.exists(dest):
shutil.rmtree(dest)
os.mkdir(dest)
#循环读取文件
for file in file_list:
#遍历每一个文件,改名字
#分割
s_file = file.rpartition('.')
# print(s_file)
dst_file = dest+'/'+s_file[0]+'_bak'+s_file[1]+s_file[2]
# print(dst_file)
#文件的打开
file_r=open(file,'rb')
file_w=open(dst_file,'wb')
#读取内容
while True:
con = file_r.read(4096)
if con ==b'':
print(f'{src}{file} 复制成功')
file_r.close()
file_w.close()
break
file_w.write(con)
print(f'一共复制了{len(file_list)}个文件')
src = 'D:/pycharmwork/copy/a'
dest = 'D:/pycharmwork/copy/b'
copy_file(src,dest)