在python中打开具有特定类型的文件
我想在用户输入以下特定文件类型的目录中打开文件:在python中打开具有特定类型的文件,python,glob,file-type,Python,Glob,File Type,我想在用户输入以下特定文件类型的目录中打开文件: if type is not None: for file in glob.glob(dir + "/" + type): if os.path.isfile(file): open_file(file) if os.path.isdir(file): open_folder(file) Type是“t”,作为代表文件类型的参数解析器变量,D是dir: $
if type is not None:
for file in glob.glob(dir + "/" + type):
if os.path.isfile(file):
open_file(file)
if os.path.isdir(file):
open_folder(file)
Type是“t”,作为代表文件类型的参数解析器变量,D是dir:
$ python scan.py -D /home/ -t .php
但它只是给出一个空输出,而不是.php文件的预期结果
请试试这个
import glob
path = "/home/yourdir/*.php"
for filename in glob.glob(path, recursive=True):
with open(filename, 'r') as f:
for line in f:
print line,
更多信息。可能是您想要的
安装path.py
pip install path.py
并使用带有模式的WalkFile
import path
D = "/home/yourdir"
T = ".php"
for filename in path.Path(D).walkfiles(pattern= "*"+T):
print(filename)
因此,您的glob语句是
glob.glob('/home//php')
您希望它能找到什么?尝试在glob模式glob.glob(dir+'/*.+type)的文件扩展名之前添加一个通配符我怀疑您想要递归globglob.glob(base_dir+“/***.+my_type,recursive=True)
您应该使用os.path.join
而不是手动连接字符串。如果操作正确,它将为您购买更干净的代码和跨平台代码。同样使用变量名,它是一个内置名称。***
是globstar模式,***//code>将匹配当前目录和当前路径下的所有子目录,其余的*。
如您所料recursive=True
参数是python启用globstar所必需的,因为它意味着性能影响,这与globstar的场景类似,但用途不同。路径和类型由用户指定。当目录中包含太多子文件夹时,我的代码被卡住了,它不会给出@Shailesh文件类型