本文是测试开发工程师 Venn 同学面试某互联网名企遇到的一道面试题目,首发于 Testerhome 社区,引发了有趣的讨论和解答,供各位测试同学参考。链接:testerhome.com/topics/1833…
一道有趣的测试面试题目
**题目:**在 A 文件夹下有多个子文件夹(a1、b1、c1),每个子文件夹下有好几张 jpg 图片,要求写一段代码(用 Python or Shell),把这些图片全部拷贝并存在 B 文件夹下。
聪明的 Cookie** 同学:考点就是如何遍历一个文件夹下的文件,需要考虑的是文件路径深度,需要用到递归。
**诚实的 **黑山老妖同学:我觉得对我来说,难点是操作文件的方法,之前没怎么用过,递归遍历啥的倒是小问题。
爆炸的 hellohell 同学:我再想,如果我碰到这个问题,是否能当场给出正确答案?估计不成,因为 API 全忘掉了。确实记性不好。如果给我个本儿,给上网机会,多费点时间,能搞出来;甚至用了递归,生成器,精简了代码(篡成一行),做了判断。
- jpg 是个目录咋办?- 不同目录下文件同名咋办?- 以及其他

参考答案
Python 解答(by 煎饼果子)
# -*- 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()
Java 解答(by Lucas)
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);-}
Shell 解答(by 杰)
find ./A/ -maxdepth 2 -name '*.jpg' -exec cp {} ./B \;


