
- 一、文件
- 1.作用:进行持久化存储数据
- 2.程序 *** 作过程
- 3.文件读取
- 4.文件重命名rename
- 5.创建目录mkdir
- 6.获取当前目录getcwd
- 7.获取当前目录下的文件列表listdir
- 8.改变当前目录到指定路径上chdir
- 9.删除文件remove
- 10.删除目录rmdir
- 二、练习
- 1.复制文件
- 2.文件批量重命名并复制到另一个文件
`
一、文件 1.作用:进行持久化存储数据 2.程序 *** 作过程- 打开:设置打开的模式(读,写)
- *** 作文件(读取)
- 关闭:close()
- file.read()默认全部读取,适用于比较小的文件
- file.read(5)
file.read(5)
file.read(5)# 接着读取
- 读取多行文件的方式
while True:
content = file.read(1)# 一般设置4096---4k
if content == '':# 设置文件读取的结束条件
break
print(content)
- readline()以行读取
- readlines()将文件内容以行读取并形成列表
- 导入os模块( *** 作系统)
- os.rename(原名,修改后的名)
- os.mkdir(目录名)
- 如果目录已存在会报错
- os.getcwd() 返回值是当前目录
- .当前目录
- …上级目录
- os.listdir(‘.’)返回的列表
- os.chdir(‘路径’)
c:\users\kg\desktop
- os.remove(路径’')
- os.rmdir(‘路径’)
当目录不为空时不能删除
def file_copy(src,dst):
file_r = open(src,'r')# open(src,'rb')判断二进制文件写法
file_w = open(dst,'w')# open(dst,'wb')判断二进制文件写法
while True:
content = file_r.read(4096)
if content == '':# content == b''判断二进制文件写法
print("拷贝成功")
break
file_w.write(content)
file_r.close()
file_w.close()
print(sys.argv)
src = sys.argv[0]
dst = sys.argv[1]
file_copy(src,dst)
2.文件批量重命名并复制到另一个文件
import os
def all_copy_rename(src,dst):
os.chdir(src)
print(os.getcwd())
file_list = os.listdir('.')
for file in file_list:
p_file = file.rpartition('.')
dst_file = dst + '/' + p_file[0]+'--'+p_file[1]+p_file[2]
print(dst_file)
file_r = open(file,'rt')
file_w = open(dst_file,'wt')
while True:
content = file_r.read(1024)
if content == '':
print(f"{file}复制成功")
file_w.close()
file_r.close()
break
file_w.write(content)
else:
print(f"一共复制了{len(file_list)}")
src = "C:/Users/yoki/Desktop/vv"
dst = "C:/Users/yoki/Desktop/v"
all_copy_rename(src,dst)
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)