递归某目录下所有文件,以及打印出这些文件的上一级目录,文件名和后缀名等.
import os
def recur_files(path):
pcd_lst = []
label_lst = []
parents = os.listdir(path)
for parent in parents:
child = os.path.join(path,parent)
if os.path.isdir(child):
recur_files(child)
else:
print(os.path.dirname(child))#parent folder
basename, ext = os.path.splitext(os.path.basename(child))
print(basename)#filename
print(ext)#extention,include'.'
加上统计某一后缀文件个数功能:
import os
count = 0
def recur_files(path):
global count
parents = os.listdir(path)
for parent in parents:
child = os.path.join(path,parent)
if os.path.isdir(child):
recur_files(child)
else:
basename, ext = os.path.splitext(os.path.basename(child))
if ext == '.pcd':
count += 1
return count
import os
pcd_lst = []
label_lst = []
def recur_files(path):
for root, _, files in os.walk(path):
for file in files:
if file.endswith(".pcd"):
pcd_lst.append(os.path.join(root, file))
if __name__ == '__main__':
my_dir = os.getcwd()
recur_files(my_dir)
label_lst = [p.replace('pcds', 'labels') for p in pcd_lst]
label_lst = [l.replace('.pcd', '.json') for l in label_lst]
assert(len(pcd_lst) == len(label_lst))
length = len(pcd_lst)
with open(os.path.join('train_list.txt'),'wb') as fin:
for i in range(length):
fin.write(pcd_lst[i] + " " + label_lst[i] + "\n")
再来个批量重命名文件:
import os
def recur_files(path):
global count
parents = os.listdir(path)
for parent in parents:
child = os.path.join(path,parent)
if os.path.isdir(child):
recur_files(child)
else:
basename, ext = os.path.splitext(os.path.basename(child))
if ext == '.mp3':
os.rename(basename+ext,basename.replace(' [mqms]','') +ext)
#count += 1
if __name__ == '__main__':
recur_files(os.getcwd())
批量复制文件到某一盘符/文件夹:
import shutil
count = 0
def recur_files(path):
global count
parents = os.listdir(path)
for parent in parents:
child = os.path.join(path,parent)
if os.path.isdir(child):
recur_files(child)
else:
basename, ext = os.path.splitext(os.path.basename(child))
if ext == '.mp3':
count += 1
#print(os.path.dirname(child)+ "\\" + basename+ext)
shutil.copy(os.path.dirname(child)+ "\\" + basename+ext, r"G:")
#count += 1
if __name__ == '__main__':
recur_files(os.getcwd())
参考:震惊!Python竟然是这样的修改全局变量