1.修改当前目录为指定目录
- os.chdir(path)
import os
# 将当前工作目录切换为 c:\windows
os.chdir('c:/windows')
- 路径输入方式:
- / :将正常路径中的斜杠以此替代,路径正确识别
- \\ :将正常路径中的斜杠以双斜杠代替,其增加的一个斜杠起转义作用
- r :直接在引用的正常路径前加上r,以让系统将后方路径识别为字符串
# “/”模式路径
path = 'c:/windows'
# “//”模式路径
path = 'c:\\windows'
# "r"模式路径
path = r'c:\windows'
2.获取当前目录路径
- os.getcwd()
os.getcwd()
# 输出
c:\\windows
3.路径拼接
- os.path.join(path1,path2…)
- 注:
- 各path间’\‘由系统自动补全,拼接以第一个带“\”开头的path开始,在此之前的path将被忽略
- 如果最后一个path为空,则以“\”补全,中间path为空时,不起作用
path1 = '\\Users'
path2 = 'Leon'
path3 = 'Desktop'
path4 = ''
path = os.path.join(path1, path2, path3, path4)
print('c:' + path )
# 输出
c:\Users\Leon\Desktop\
path = os.path.join(path2, path1, path4, path3)
print('c:' + path )
# 输出
c:\Users\Desktop
4.返回指定文件夹包含的所有文件或文件夹的列表
- os.listdir(path)
- 注:当不指定path时,则返回当前路径下的所有文件或文件夹的列表
os.listdir()
# 输出
['11','Learn.lnk','微信双开.bat', '新建 Microsoft Excel 工作表 (2).xlsx', '新建 Microsoft Excel 工作表.xlsx', '新建文件夹', '新建文本文档.txt']
- os.scandir()
- 在 Python 3.5版本中,新添加了 os.scandir()方法,它是一个目录迭代方法。低于3.5版本的Py是无法使用的
for file in os.scandir():
print(file.name, file.path, file.is_dir())
# 输出
文件夹名称、路径、是否为文件夹
5.判断文件夹
- os.path.isdir(path)
- 注:当不指定path时,判断当前路径
os.path.isdir(r'c:\Users\Leon\Desktop\11')
# 输出
True
6.判断文件
- os.path.isfile(path)
- 注:当不指定path时,判断当前路径
os.path.isfile(r'c:\Users\Leon\Desktop\11')
# 输出
False
7.遍历文件夹
7.1 os.listdir + 递归
import os
image_path = 'c:/test'
# 遍历文件夹及其子文件夹中的文件,并存储在一个列表中
# 输入文件夹路径,空文件列表
# 返回文件列表Filelist,包含文件名(完整路径)
def get_filelist(dir, Filelist):
newDir = dir
if os.path.isfile(dir):
Filelist.append(dir)
# 若只要返回文件名,则:Filelist.append(os.path.basename(dir))
elif os.path.isdir(dir):
for s in os.listdir(dir):
# 若需忽略某些文件夹,添加以下代码
# if s == "xxx":
# countiue
newDir = os.path.join(dir, s)
get_filelist(newDir, Filelist)
return Filelist
if __name__ == '__main__':
list = get_filelist('c:/test', [])
print(len(list))
for e in list:
print(e)
7.2 os.walk
- os.walk(top, topdown=Ture, οnerrοr=None, followlinks=False)
import os
j = 0
for folders, subfolders, filelists in os.walk('c:/test'):
for file in filelists:
print(folders + file)
j += 1
print(f'共有{j}个文件')
7.3 os.scandir + 递归
8. 搜索、匹配文件名称
8.1 利用字符串方法:startswith()、endswith()
import os
for file in os.scandir('c:/test'):
if file.name.endswith('.xlsx') or file.name.startswith('.xls'):
print(file.name)
8.2 glob模块
import glob
import os
os.chdir('c:/test')
# 查找当前文件夹中符合条件的文件
print(glob.glob('新建*[!0-9].xls*'))
# 查找当前文件夹及其子文件夹中符合条件的文件
print(glob.glob('**/新建*[!0-9].xls*', recursive=True))
# glob.iglob 返回可遍历对象
filenames = glob.iglob(('**/新建*[!0-9].xls*', recursive=True))
for filename in filenames:
print(filename)
8.3 fnmatch模块
- fnmatch 返回的是布尔值(True/False)
import os
import fnmatch
dirs = os.listdir('c:/test')
for filenames in dirs:
if fnmatch.fnmatch(filenames,''):
print(filenames)
9. 创建文件夹
9.1 单层
- os.mkdir(path)
import os
path = os.getcwd()
path = path + r'\Leon'
if not os.path.exists(path):
os.mkdir(path)
else:
print('此文件夹已存在')
- 自建函数方式创建文件夹
import os
def makedir(path):
dir = os.path.basename(path)
if not os.path.exists(path):
os.mkdir(path)
print('文件夹创建成功' + dir)
return True
else:
print('此文件夹已存在' + dir)
return False
if __name__ == '__main__':
makedir('c:/test/Leon')
9.2 多层
- os.makedirs(path)
import os
os.makedirs('c:/test/Leon/test1')
- 自建函数方式创建文件夹(适用于单层和多层)
import os
def mkdirs(path):
if not exists(path):
makedirs(path)
print('文件夹创建成功!')
return True
else:
print('此文件夹已存在')
return False
if __name__ == '__main__':
mkdirs('c:/test/Leon/test2')
10. 复制文件
- shutil.copy(oldfile_path,newpath)
- shutil.copy会改变复制文件的创建时间(可使用copy2使复制文件与原文件的创建时间保持一致)
- 复制时,新路径的文件夹必须存在
- 可在新路径中修改文件名,以达到修改文件名的效果
- 如果oldfile_path和newpath是同一文件,就会引发错误shutil.Error
- newpath必须是可写的,否则将引发异常IOError。如果dst已经存在,它会被替换
import os
import shutil
oldfile_path = 'c:/test/test.txt'
newpath = 'c:/test/Leon'
shutil.copy(oldfile_path, newpath)
# 复制并修改文件名
newpath = 'c:/test/Leon/test1.txt'
shutil.copy(oldfile_path, newpath)
11. 复制文件夹
- shutil.copytree(oldfolder,newfolder)
- oldfolder与newfolder处于同一文件夹下时,不同相同
import shutil
shutil.copytree(''c:/test','c:/test/Leon')
12.移动文件和文件夹
- shutil.move(oldfile_path,newpath)
- newpath必须是实际存在的文件夹
- 可在新路径中修改文件名,以达到修改文件名的效果
import shutil
shutil.move('c:/test/Leon/test1.txt','c:/test/Leon')
# 移动并修改文件名
shutil.move('c:/test/Leon/test1.txt','c:/test/Leon/test2.txt')
# 移动文件夹
shutil.move('c:/test/Leon','c:/test/shirley')
13. 删除文件夹
shutil.rmtree(path)
import shutil
shutil.rmtree('c:/test/shirley')
14. 删除文件
- os.remove(path)
import os
os.remove('c:/test/Leon/test1.txt')
15. 重命名文件及文件夹
- os.rename(oldpath,newpath)
# 重命名
os.remame('c:/test/Leon/test1.txt','c:/test/Leon/test2.txt')
os.remame('c:/test/shirley','c:/test/lisa')
# 移动并重命名
os.remame('c:/test/Leon/test1.txt','c:/test/shirley/test2.txt')
os.remame('c:/test/shirley','c:/test1/lisa')
16.获取文件属性
- os.stat(path)
- st_mode: inode 保护模式
- st_ino: inode 节点号
- st_dev: inode 驻留的设备
- st_nlink: inode 的链接数
- st_uid: 所有者的用户ID
- st_gid: 所有者的组ID
- st_size: 普通文件以字节为单位的大小;包含等待某些特殊文件的数据
- st_atime: 上次访问的时间
- st_mtime: 最后一次修改的时间
- st_ctime: 由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)
17.文件读写
模式:
- r:只读,如果文件不存在,则报错,只读不写,光标位置为文件开头
- w:写入,如果文件不存在,则新建文件,写入时覆盖原内容,光标位置为文件开头
- a:追加,如果文件不存在,则新建文件,写入时在原有内容的基础上追加新内容,光标位置为文件结尾
- b:二进制,可与r、w、b连用
- +:可读可写,可与r、w、b连用
读取方法
- 文件对象. read(num):
- num:读取的长度(单位字节),若不填则读取所有数据
- 文件对象. readlines()
- 需要赋值给一个变量
- 读取整个文件,并回列表,每一行为列表中的一个元素,包括换行符\n
- 文件对象. readline()
- 需要赋值给一个变量
- 一次读取一行,不包括换行符\n
with语句
# 读取
with open('c:/test/Leon/test2.txt','r', encoding='utf-8') as fp:
print(fp.readlines())
# 写入
with open('c:/test/Leon/test2.txt','w') as fp:
fp.write('one\ntwo\nthree\nfour\n')
使用pandas读写文件
import pandas as pd
path = 'c:/test/Leon/test2.txt'
# 读取
data = pd.read_csv(path)
# 写入
pa.to_csv('c:/test/test3.txt')