【发布时间】:2018-04-23 12:52:15
【问题描述】:
如何检查某个文件夹中是否存在任何文件?我知道如何检查 A 文件。如下
a = os.path.exists("text.txt")
if a:
print("file is there")
else:
print("not found")
提前致谢
【问题讨论】:
标签: python
如何检查某个文件夹中是否存在任何文件?我知道如何检查 A 文件。如下
a = os.path.exists("text.txt")
if a:
print("file is there")
else:
print("not found")
提前致谢
【问题讨论】:
标签: python
使用os.listdir
例如:
import os
if os.listdir(path):
print("file is there")
else:
print("not found")
【讨论】:
将列出文件夹folder中的文件
脚本从main运行
folder
files
...
main.py
将仅列出文件,而不是 . 和 ..
import os
dir = os.path.dirname(__file__) or '.'
dir_path = os.path.join(dir, '../folder/')
onlyfiles = [f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))]
【讨论】:
folder = os.listdir("/home/yourname/yourdir")
if len(folder)>0:
print "the folder is not empty"
【讨论】: