求职 面试京东金融被问到的题目,希望大家求解。

venn · 2019年03月01日 · 最后由 海棠不是朵朵 回复于 2019年03月04日 · 1871 次阅读

题目:A 文件夹下有多个子文件夹(a1 b1 c1),每个子文件夹下有好几张 jpg 图片,需要把这个这些图片全部拷贝并存在 B 文件夹下。

最佳回复

这样写 可以不

# -*- coding: utf-8 -*-
import os,shutil

def movefile(srcfile,dstfile):
    fpath,fname=os.path.split(srcfile)
    if os.path.isfile(os.path.join(dstfile,fname)):
        print("%s exist!"%str(os.path.join(dstfile,fname)))
    elif not os.path.isfile(srcfile):
        print("%s not exist!")%(srcfile)
    else:
        fpath,fname=os.path.split(dstfile)
        if not os.path.exists(fpath):
            os.makedirs(fpath)
        shutil.move(srcfile,dstfile)

def getfile(path):
    paths = []
    for root, dirs, files in os.walk(path):
        for file in files:
            paths.append(os.path.join(root,file))
    return paths

def main():
    path = "/path/A"
    pathto = "/path/B"
    paths = getfile(path)
    for pathfrom in paths:
        print(pathfrom)
        movefile(pathfrom,pathto)

if __name__ == '__main__':
    main()
public void copyImages(File from, File to) throws IOException {
    if(from == null || to == null) {
        throw new RuntimeException("From or To is empty.");
    }

    if(from.isFile()) {
        throw new RuntimeException("From is not directory.");
    }

    if(to.isFile()) {
        throw new RuntimeException("To is not directory.");
    }

    File[] images = from.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            boolean result = false;
            if(pathname.isFile()) {
                String path = pathname.getAbsolutePath().toLowerCase();
                if(path.lastIndexOf(".jpg") > -1
                    || path.lastIndexOf(".png") > -1
                    || path.lastIndexOf(".jpeg") > -1
                    || path.lastIndexOf(".bmp") > -1) {

                    result = true;
                }
            } else {
                result = false;
            }
            return result;
        }
    });

    for(File image : images) {
        copyImagesHelper(image, to);
    }

    File[] dirs = from.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });

    for(File dir : dirs) {
        copyImages(from, to);
    }
}

private void copyImagesHelper(File image, File dir) throws IOException {
    String cmd =
        String.format("cp %s %s", image.getAbsolutePath(), dir.getAbsolutePath());
    Runtime runtime = Runtime.getRuntime();
    runtime.exec(cmd);
}
共收到 22 条回复 时间 点赞

这是考 shell?

find  ./A/ -maxdepth 2  -name '*.jpg' -exec cp {} ./B \;
for file in `find /A -name "*.jpg"`;do mv $file /B;done
venn #3 · 2019年03月01日 Author
YueChen 回复

应该是 当时面试官让我用 python 写😢

venn #4 · 2019年03月01日 Author

这样的题目 能用语言写不 。

这样写 可以不

# -*- coding: utf-8 -*-
import os,shutil

def movefile(srcfile,dstfile):
    fpath,fname=os.path.split(srcfile)
    if os.path.isfile(os.path.join(dstfile,fname)):
        print("%s exist!"%str(os.path.join(dstfile,fname)))
    elif not os.path.isfile(srcfile):
        print("%s not exist!")%(srcfile)
    else:
        fpath,fname=os.path.split(dstfile)
        if not os.path.exists(fpath):
            os.makedirs(fpath)
        shutil.move(srcfile,dstfile)

def getfile(path):
    paths = []
    for root, dirs, files in os.walk(path):
        for file in files:
            paths.append(os.path.join(root,file))
    return paths

def main():
    path = "/path/A"
    pathto = "/path/B"
    paths = getfile(path)
    for pathfrom in paths:
        print(pathfrom)
        movefile(pathfrom,pathto)

if __name__ == '__main__':
    main()
venn #6 · 2019年03月01日 Author

可以了,很快的。谢谢大佬👍
不过你的代码 我有点看不懂,你是学了多久 python 的

venn #7 · 2019年03月01日 Author

看了下生成的 B 文件,还有其他格式文件。是要加 *.jpg 吧

考点就是如何遍历一个文件夹下的文件,需要考虑的是文件路径深度,需要用到递归

venn #9 · 2019年03月01日 Author
cookie 回复

是的,遍历加复制。刚才用楼上的代码运行 是移动,幸好不是工作文件

是的,你可以对文件格式进行限制

def getfile(path):
    paths = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if os.path.splitext(file)[1] == '.jpg':
                paths.append(os.path.join(root,file))
    return paths

如果是复制的话,把shutil.move() 改成shutil.copy() 即可

请把文件和文件夹区分清除,不知道的还以为是多个文件合并成一个文件呢 [手动笑哭]

我觉得对我来说,难点是操作文件的方法,之前没怎么用过,递归遍历啥的倒是小问题

这个如果是面测试,这个肯定还需要你提问的(考你需求分析),不仅仅是说写个脚本,等你写完了(考你编程熟悉),还会让你针对你写的代码进行测试(考你用例设计),都是套路

venn #14 · 2019年03月01日 Author

感谢感谢,我研究下代码去。

venn #15 · 2019年03月01日 Author
剪烛 回复

哈哈哈 ,多谢提醒。失误失误

venn #16 · 2019年03月01日 Author
剪烛 回复

确实是这样子,越问越深的。总之面试的时候不能让面试官带着自己走。

venn #17 · 2019年03月01日 Author
黑山老妖 回复

看看 5 楼的代码 很赞的

public void copyImages(File from, File to) throws IOException {
    if(from == null || to == null) {
        throw new RuntimeException("From or To is empty.");
    }

    if(from.isFile()) {
        throw new RuntimeException("From is not directory.");
    }

    if(to.isFile()) {
        throw new RuntimeException("To is not directory.");
    }

    File[] images = from.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            boolean result = false;
            if(pathname.isFile()) {
                String path = pathname.getAbsolutePath().toLowerCase();
                if(path.lastIndexOf(".jpg") > -1
                    || path.lastIndexOf(".png") > -1
                    || path.lastIndexOf(".jpeg") > -1
                    || path.lastIndexOf(".bmp") > -1) {

                    result = true;
                }
            } else {
                result = false;
            }
            return result;
        }
    });

    for(File image : images) {
        copyImagesHelper(image, to);
    }

    File[] dirs = from.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory();
        }
    });

    for(File dir : dirs) {
        copyImages(from, to);
    }
}

private void copyImagesHelper(File image, File dir) throws IOException {
    String cmd =
        String.format("cp %s %s", image.getAbsolutePath(), dir.getAbsolutePath());
    Runtime runtime = Runtime.getRuntime();
    runtime.exec(cmd);
}
venn #19 · 2019年03月01日 Author
卡农Lucas 回复

大佬啊 这么赞的,社区真是人才济济 谢谢啦

在想,如果我碰到这个问题,是否能当场给出正确答案?估计不成,因为

  • api 全忘掉了。确实记性不好。如果给我个本儿,给上网机会,多费点时间,能搞出来;甚至用了递归,生成器,精简了代码(篡成一行),做了判断
    • jpg 是个目录咋办?
    • 不同目录下文件同名咋办?
    • 以及其他

但 前提是你不参考任何东西就写代码。但实际工作中好像这种人不多;so,我只能原地爆炸了

不过打心里还是觉得用 shell 解决这个问题比较好些。

感觉需求不明确呀。

每个子文件夹下有好几张 jpg 图片
这个范围是包含所有级别的子文件夹,还是只需要一级的子文件夹?

需要把这个这些图片全部拷贝并存在 B 文件夹下
文件夹结构需要一起拷贝不?没有提及。

for cfile in `find APATH -name "*.jpg"`;do cp $cfile BPATH;done

venn 关闭了讨论 03月04日 16:47
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册