python OS 文件/目录常用方法总结

1
2
3
4
5
6
7
8
9
10
11
os.makedirs(path[, mode]) 
递归文件夹创建函数。像mkdir(), 但创建的所有intermediate-level文件夹需要包含子文件夹。

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
输出在文件夹中的文件名通过在树中游走,向上或者向下。返回的是一个三元组(root,dirs,files),是一个生成器类型,需要用for遍历读取

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

os.listdir(path)
返回path指定的文件夹包含的文件或文件夹的名字的列表。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
import os
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

path = "/var/www/html/"
dirs = os.listdir( path )
# 输出所有文件和文件夹
for file in dirs:
print (file)

os.walkos.listdir两个函数的区别在于前者会遍历到子文件夹中的子文件,而后者只是返回你传入的path中的文件夹名字和文件名字。

os库中有一个path的模块,专门用于处理文件path相关的属性信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
os.path.abspath(path)
返回绝对路径

os.path.basename(path)
返回文件名

os.path.exists(path)
如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。

os.path.join(path1[, path2[, ...]])
把目录和文件名合成一个路径

os.path.split(path)
把路径分割成 dirname 和 basename,返回一个元组

os.path.splitext(path)
分割路径,返回路径名和文件扩展名的元组

os.path.walk(path, visit, arg)
遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数

例子:

1
2
3
4
5
6
7
import os

print( os.path.basename('/root/runoob.txt') ) # 返回文件名
print( os.path.dirname('/root/runoob.txt') ) # 返回目录路径
print( os.path.split('/root/runoob.txt') ) # 分割文件名与路径
print( os.path.join('root','test','runoob.txt') ) # 将目录和文件名合成一个路径
print( os.path.splitext('/root/runoob.txt') )
1
2
3
4
5
runoob.txt
/root
('/root', 'runoob.txt')
root/test/runoob.txt
('/root/run/test', '.txt')

上面的split和splitext,前者分割出了文件名和路径,而后者可以分割出路径名和扩展名,如果想要获得文件的扩展名,可以用splitext,传入文件的path就可以了。

1
os.mknod(filename) 创建

复制文件和删除文件,移动文件

如果是删除一个目录,可以使用以下两种方式:

1
2
3
4
5
6
7
8
9
import shutil
# method 1
if os.path.exists(root_dir):
shutil.rmtree(root_dir) # 这里不可以使用os.removedirs(),removedirs只可以删除非空的文件夹,rmdir也是

# method 2
if len(os.listdir(root_dir)) > 0:
for file in os.scandir(root_dir):
os.remove(file.path)

如果想复制一个文件到另外一个文件夹,参考 https://zhuanlan.zhihu.com/p/35725217

1
copyfile(source_file, destination_file)

记住这里第二个参数一定要是可写入的文件名字,而不是目录。

移动文件

1
2
3
4
5
6
7
8
9
10
import shutil
import os

file_source = 'Path/Of/Directory'
file_destination = 'Path/Of/Directory'

get_files = os.listdir(file_source)

for g in get_files:
shutil.move(file_source + g, file_destination)

读写csv文件

第一个方式是用pandas,具体不介绍。

这里总结一下csv库

1
2
3
4
5
6
7
8
9
10
# 读取csv文件
with open(filename,'r') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
print(row[1]) # 用列表的index取值
# 写csv文件
with open(filename,'w') as csvfile:
csv_writer = csv.writer(csvfile)
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) # writerow接受一个list,所有值都会写在一行里
spamwriter.writerows([[],[],[]]) # writerows写入多行,每一行是一个列表,传进去的是列表的列表

除了写入list,还可以写字典类型的数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# my data rows as dictionary objects 
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]

# field names
fields = ['name', 'branch', 'year', 'cgpa']

# name of csv file
filename = "university_records.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames = fields)

# writing headers (field names)
writer.writeheader()

# writing data rows
writer.writerows(mydict)