我试图只获取文件夹中的文件,不包括任何其他目录。但下面的脚本将所有文件和文件夹移动到另一个目录。
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)
最佳答案
在 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__')
此外,您可以使用 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('----------------------')
关于python - 区分Python中的文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507133/