操作文件os

操作文件和目录一般要用到 os 库。下面介绍一些 os 库的函数。

### 获取当前工作目录
os.getcwd()

### 改变工作目录
os.chdir(path)

### 创建目录
os.mkdir(path)

### 返回 path 的绝对路径
os.path.abspath(path)

### 将 path 分割成目录和文件名二元组返回
os.path.split(path)

### 分离文件名与扩展名
os.path.splitext(path)
>>> os.path.splitext('c:\\csv\\test.csv')
('c:\\csv\\test', '.csv')

### 返回 path 的目录
os.path.dirname(path)
>>> os.path.dirname('C:\\hhh\\jjj')
'C:\\hhh'
>>> os.path.dirname('C:\\hhh')
'C:\\'

### 返回 path 最后的文件名
os.path.basename(path)
>>> os.path.basename('C:\\hhh\\jjj')
'jjj'
>>> os.path.basename('C:\\hhh')
'hhh'

### 若path存在/不存在,返回True/False
os.path.exists(path)

### 若path是/不是文件,返回True/False
os.path.isfile(path)

### 若path是/不是目录,返回True/False
os.path.isdir(path)

### 将多个路径组合返回
os.path.join(path1[,path2[,...]])
>>> os.path.join('c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('windows\temp', 'c:\\', 'csv', 'test.csv')
'c:\\csv\\test.csv'
>>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c')
'/home/aa/bb/c'



### 返回 path 目录下的所有文件
os.listdir(path)

实例

os.listdir(path) 获取某个目录path下的所有文件和目录。

  • test 目录结构树
PS C:\Users\ghz1996jx\test> tree /F
卷 Windows-SSD 的文件夹 PATH 列表
卷序列号为 D4EC-01D7
C:.
│  file1.txt
│  file2.txt
│
├─dir1
├─dir2
│      file2_1.txt
│
└─dir3
    └─dir3_1
            file3_1_1.txt
>>> import os
>>> os.getcwd()
'C:\\Users\\ghz1996jx\\test'
>>> os.path.dirname(os.getcwd())
'C:\\Users\\ghz1996jx'
>>> os.path.basename(os.getcwd())
'test'
>>> os.listdir(os.getcwd())
['dir1', 'dir2', 'dir3', 'file1.txt', 'file2.txt']
>>> for i in os.listdir(os.getcwd()):
...     if os.path.isfile(i):
...             print(os.path.abspath(i))
...
C:\Users\ghz1996jx\test\file1.txt
C:\Users\ghz1996jx\test\file2.txt
>>> for i in os.listdir(os.getcwd()):
...     if os.path.isfile(i):
...             print(os.path.abspath(i))
...     if os.path.isdir(i):
...             for j in os.listdir(i):
...                     print(os.path.abspath(j))
...
C:\Users\ghz1996jx\test\file2_1.txt
C:\Users\ghz1996jx\test\dir3_1
C:\Users\ghz1996jx\test\file1.txt
C:\Users\ghz1996jx\test\file2.txt

os.walk 输入一个路径名称,以 yield 的方式(其实是一个生成器)返回一个三元组 dirpath, dirnames, filenames

>>> for i,j,k in os.walk(os.getcwd()):
...     print(i,j,k)
...
C:\Users\ghz1996jx\test ['dir1', 'dir2', 'dir3'] ['file1.txt', 'file2.txt']
C:\Users\ghz1996jx\test\dir1 [] []
C:\Users\ghz1996jx\test\dir2 [] ['file2_1.txt']
C:\Users\ghz1996jx\test\dir3 ['dir3_1'] []
C:\Users\ghz1996jx\test\dir3\dir3_1 [] ['file3_1_1.txt']

>>> for i,j,k in os.walk(os.getcwd()):
...     for file in k:
...             print(os.path.abspath(file))
...
C:\Users\ghz1996jx\test\file1.txt
C:\Users\ghz1996jx\test\file2.txt
C:\Users\ghz1996jx\test\file2_1.txt
C:\Users\ghz1996jx\test\file3_1_1.txt