我在目录中有文件列表。我想遍历文件名并在找到特定文件扩展名时调用函数
def files():
files = os.listdir()
# files = ['abc.Jpg','ferf.jpg','vber.pdf','uvier.xlsx']
for file in files:
if file.lower().endswith('.jpg'):
name= Dict['jpg']
name(file)
elif file.lower().endswith('.pdf'):
e= Dict['pdf']
e(file)
elif file.lower().endswith('.xlsx'):
f= Dict['xlsx']
f(file)
else:
print('no file found')
return
def jpg(d):
print('image file found {}'.format(file))
def pdf(e):
print('pdf file found {}'.format(file))
def xlsx(f):
print('excel file found {}'.format(file))
Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx }
files()
这是我的代码。我在这里面临两个问题。
为什么此代码有误?预先感谢
答案 0 :(得分:2)
您从function参数中使用了错误的参数,应从return
语句中删除else
:
正确的代码将是:
import os
def files():
files = os.listdir()
file_found_flag = False
for file in files:
if file.lower().endswith('.jpg'):
name= Dict['jpg']
name(file)
file_found_flag = True
elif file.lower().endswith('.pdf'):
e= Dict['pdf']
e(file)
file_found_flag = True
elif file.lower().endswith('.xlsx'):
f= Dict['xlsx']
f(file)
file_found_flag = True
if not file_found_flag:
print('no file found')
def jpg(file):
print('image file found {}'.format(file))
def pdf(file):
print('pdf file found {}'.format(file))
def xlsx(file):
print('excel file found {}'.format(file))
Dict={"jpg":jpg, "pdf":pdf,"xlsx":xlsx }
files()
答案 1 :(得分:0)
您可以像这样干净地做
// gulpfile.js
const imageminMozjpeg = require('imagemin-mozjpeg');
const pngquant = require('imagemin-pngquant');
const imagemin = require('gulp-imagemin');
const imageminJpegRecompress = require('imagemin-jpeg-recompress');
const webp = require('imagemin-webp');
const extReplace = require('gulp-ext-replace');
const gulp = require('gulp');
const watch = require('gulp-watch');
gulp.task('optimize_image', () =>
gulp.src(['uploads/products/**/*',
'uploads/banner_image/*',
'uploads/varient_images/**/*'],{base: 'uploads/'})
.pipe(imagemin([
pngquant({quality: [0.5, 0.5]}),
imageminMozjpeg({quality: 50}),
imagemin.jpegtran({progressive:true})
]))
.pipe(gulp.dest('uploads/'))
);
gulp.task("exportWebP", function() {
let src = ['uploads/**/*.jpg']; // Where your jpgs are coming from.
let dest = "uploads/"; // Where your WebPs are going.
return gulp.src(src)
.pipe(imagemin([
webp({
quality: 50
})
]))
.pipe(extReplace(".webp"))
.pipe(gulp.dest(dest));
});
gulp.task('watcher', function(){
gulp.watch('uploads/**/*.jpg', gulp.parallel('exportWebP'));
console.log('Running watch...');
});
gulp.task('default', gulp.series('optimize_image', 'exportWebP', 'watcher'));
答案 2 :(得分:0)
我注意到您的代码中有几处可能是错误的:
文件是Python内置的。您可能需要将变量名更改为文件以外的其他名称。
for f in files:
if f.lower().endswith('.jpg'):
name= Dict['jpg']
name(f)
elif f.lower().endswith('.pdf'):
e= Dict['pdf']
e(f)
elif f.lower().endswith('.xlsx'):
func= Dict['xlsx']
func(f)
else:
print('no file found')
return
您在jpeg,xlsx和pdf方法中使用了错误的参数。
def jpg(d): print('找到图像文件{}'。format(d))
在我的情况下产生的输出:
image file found abc.Jpg
image file found ferf.jpg
pdf file found vber.pdf
excel file found uvier.xlsx