imgfiles = []
for path, dirs, files in os.walk("."):
imgfiles.extend([os.path.join(path, f) for f in files if f.endswith('.jpg')])
追问太厉害了!!!果然是大神啊,我搞了好几个小时写了两个小时了,写那么多代码还有问题,您这三行代码就解决问题了,不佩服不行啊,我还有个问题啊,这个代码得到了文件完整路径名的列表了,我要把这里面每项写在一个文件的一行,不能很乱地堆积在一行,怎么来操作呢?另外,您这个代码是检查jpg的文件,若是我要其他格式的文件呢,就是只要是文件就得到其完整路径名,怎么办呢?非常感谢您了
追答import os
def iterfiles(walkhome, fileext=None):
for path, dirs, files in os.walk(walkhome):
for fullname in (os.path.join(path, f) for f in files):
if not fileext or fullname.endswith(fileext):
yield fullname
with open("fileslist.log", 'wt') as store:
for fullname in iterfiles(".", fileext=".txt"):
store.write(fullname+'\n')
or
import os
import fnmatch
def iterfiles(walkhome, fmx="*.*"):
"""
args:
walkhome: start path
fmx: filename shell-style wildcards
"""
for path, dirs, files in os.walk(walkhome):
for filename in fnmatch.filter(files, fmx):
yield os.path.join(path, filename)
with open("fileslist.log", 'wt') as store:
for fullname in iterfiles(".", "*.py"):
store.write(fullname+'\n')
追问非常感谢您!不好意思还有个问题,将读取的内容以utf-8格式写在文件中怎么操作?我记得python默认编码是ascii,这个编码问题太头疼了,总是搞不好,最后一个问题了,不好意思,非常感谢您!!
追答#!/usr/bin/env python
# coding: utf-8
import os
import fnmatch
import codecs
os_charset = 'utf-8' # in Windows os, usage "gb18030" instead of
def iterfiles(walkhome, fmx="*.*"):
"""
args:
walkhome: start path
fmx: filename shell-style wildcards
"""
for path, dirs, files in os.walk(walkhome):
for filename in fnmatch.filter(files, fmx):
yield os.path.join(path, filename)
with codecs.open("fileslist.log", 'w', 'utf-8') as store:
for fullname in iterfiles("/home/tim/Workspace", "*.pdf"):
store.write(fullname.decode(os_charset)+'\n')