擅长:python、mysql、java
<p>您可以使用os模块首先列出目录中的所有内容(包括文件和模块),然后使用python生成器只过滤出文件。然后可以使用第二个python生成器过滤出具有特定扩展名的文件。可能有一种更有效的方法,但这是可行的:</p>
<pre><code>import os
def main():
path = './' # The path to current directory
# Go through all items in the directory and filter out files
files = [file for file in os.listdir(path) if
os.path.isfile(os.path.join(path, file))]
# Go through all files and filter out files with .txt (for example)
specificExtensionFiles = [file for file in files if ".txt" in file]
# Now specificExtensionFiles is a generator for .txt files in current
# directory which you can use in a for loop
print (specificExtensionFiles)
if __name__ == '__main__':
main()
</code></pre>
<p>供进一步参考:
<a href="https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory">How do I list all files of a directory?</a></p>
<hr/>