C++, Python, Matlab, Bash 文件目录遍历

最近跑数据集,用到不同语言的代码,都需要遍历文件目录,可能比较常用,在这里总结一下。


#C++

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <iostream>
using namespace std;

inline void read_all_files(string path){
    DIR* FD;
    FILE *file;
    struct dirent* entry;
    
    if (NULL == (FD = opendir (path.data()))){
        fprintf(stderr, "Error : Failed to open input directory - %s\n", strerror(errno));
        return;
    }
    
    while (entry = readdir(FD)){
        if (!strcmp (entry->d_name, ".")){
            continue;}
        if (!strcmp (entry->d_name, "..")){
            continue;}
        
        string filename=path+"/"+entry->d_name;
        printf("Reading %s\n",filename.data());
        
        struct stat st;
        lstat(filename.data(), &st);
        
        if(S_ISDIR(st.st_mode)){
            printf("Type: DIRECTORY\n\n");
            read_all_files(filename); //递归调用
        }
        else{
            printf("Type: FILE\n\n");
        }
        
        file = fopen(filename.data(), "rw");
        fclose(file);
    }
}

Python

#--- Method 1 ---
from os import listdir
from os.path import isfile, join

onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

#--- Method 2 ---
path = ""
files = os.listdir(path)
for i, file in enumerate(files):
	fname = os.path.join(path, file)

#--- Method 3 ---
from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
	#print len(filenames)
	for filename in filenames:
		fullname=(os.path.join(dirpath, filename))
		f.append(fullname)

Matlab

dirname = '';
dirData = dir(dirname);
dirIndex = [dirData.isdir];  

fileList = {dirData(~dirIndex).name};
fn=size(fileList,2);
for i=1:fn
	filename = char(fileList(i));
	fullname = strcat(dirname,filename);
end

folderList = {dirData(dirIndex).name};
fn2=size(folderList,2);
for j=1:fn2
	foldername = char(folderList(j));
end


Bash

folderpath=''
files=$(find $folderpath -maxdepth 1 -mindepth 1  -name '.png'| sort )
farr=($files)
len=${#farr[*]}
echo $len
for j in $(seq 0 $[$len - 1])
do
im1=${farr[$j]}
imname=${im1##*/}
echo $imname
done
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值