一道有趣的测试面试题目
题目:
在 A 文件夹下有多个子文件夹(a1、b1、c1),每个子文件夹下有好几张 jpg 图片,要求写一段代码(用 Python or Shell),把这些图片全部拷贝并存在 B 文件夹下。
一小撮测试工程师的讨论
聪明的 Cookie 同学:考点就是如何遍历一个文件夹下的文件,需要考虑的是文件路径深度,需要用到递归。
诚实的 黑山老妖同学:我觉得对我来说,难点是操作文件的方法,之前没怎么用过,递归遍历啥的倒是小问题。
经验老道的 剪烛同学:如果拿这个题目面试测试工程师,这个肯定还需要你提问的(考你需求分析),不仅仅是说写个脚本,等你写完了(考你编程熟悉),还会让你针对你写的代码进行测试(考你用例设计),都是套路。
爆炸的 hellohell 同学:我再想,如果我碰到这个问题,是否能当场给出正确答案?估计不成,因为 API 全忘掉了。确实记性不好。如果给我个本儿,给上网机会,多费点时间,能搞出来;甚至用了递归,生成器,精简了代码(篡成一行),做了判断。
-
jpg 是个目录咋办?
-
不同目录下文件同名咋办?
-
以及其他
但前提是你不参考任何东西就写代码。但实际工作中好像这种人不多;so, 我只能原地爆炸了。
不过打心里还是觉得用 Shell 解决这个问题比较好些。
参考答案
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 \;
P.S. 以上答案仅供参考,欢迎大家在留言区,回复你的精彩解答,也许有惊喜哦
。(end)