MOH*_*S3N 5 python python-2.7 python-3.x
这是我的代码:
import os
def get_file():
files = os.listdir('F:/Python/PAMC')
print(files)
for file in files:
print(file)
get_file()
Run Code Online (Sandbox Code Playgroud)
我如何只列出python目录中的文件夹?
在 Python 3.6 中尝试并测试了以下代码
import os
filenames= os.listdir (".") # get all files' and folders' names in the current directory
result = []
for filename in filenames: # loop through all the files and folders
if os.path.isdir(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a folder or not
result.append(filename)
result.sort()
print(result)
#To save Foldes names to a file.
f= open('list.txt','w')
for index,filename in enumerate(result):
f.write("%s. %s \n"%(index,filename))
f.close()
Run Code Online (Sandbox Code Playgroud)
替代方式:
import os
for root, dirs, files in os.walk(r'F:/Python/PAMC'):
print(root)
print(dirs)
print(files)
Run Code Online (Sandbox Code Playgroud)
替代方式
import os
next(os.walk('F:/Python/PAMC'))[1]
Run Code Online (Sandbox Code Playgroud)
尝试使用生成器来os.walk
获取指定目录中的所有文件夹:
next(os.walk('F:/Python/PAMC'))[1]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14913 次 |
最近记录: |