pre*_*thi 5 python directory file
我试图只获取文件夹中不包括任何其他目录的文件。但下面的脚本将所有文件和文件夹移动到另一个目录。
while True:
# Go through each of the directories
for mylist in dirlist:
check_dir = mylist[0]
callback = mylist[1]
# get the list of files in the directory
filelist = os.listdir(check_dir)
for this_file in filelist:
if ((this_file == ".") or (this_file == "..") or (this_file == "donecsvfiles") or (this_file == "doneringofiles")):
print "Skipping self and parent"
continue
full_filename = "%s/%s"%(check_dir, this_file)
Run Code Online (Sandbox Code Playgroud)
在os.path中,有有用的isdir()和isfile()函数:
>>> import os
>>>
>>> os.path.isfile('demo.py')
True
>>> os.path.isdir('demo.py')
False
>>> os.path.isfile('__pycache__')
False
>>> os.path.isdir('__pycache__')
Run Code Online (Sandbox Code Playgroud)
另外,您可以使用os.walk()或os.scandir()自动分隔两者:
for root, dirs, files in os.walk('python/Lib/email'):
print('Searching:', root)
print('All directories', dirs)
print('All files:', files)
print('----------------------')
Run Code Online (Sandbox Code Playgroud)
您可以使用isfilefromos.path来检查路径是否是文件。此代码为您提供文件夹中的文件列表:
from os.path import isfile, join
from os import listdir
folder = 'path//to//folder'
onlyfiles = [f for f in listdir(folder) if isfile(join(folder, f))]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3560 次 |
| 最近记录: |