我有一个包含以下字符串的列表phplist
(下面的示例),还有更多,这是整个列表的片段
/home/comradec/public_html/moodle/config.php
/home/comradec/public_html/moodle/cache/classes/config.php
/home/comradec/public_html/moodle/theme/sky_high/config.php
/home/comradec/public_html/moodle/theme/brick/config.php
/home/comradec/public_html/moodle/theme/serenity/config.php
/home/comradec/public_html/moodle/theme/binarius/config.php
/home/comradec/public_html/moodle/theme/anomaly/config.php
/home/comradec/public_html/moodle/theme/standard/config.php
我要做的只是保留subdir/config.php
文件并排除所有其他config.php
文件(例如cache / classes / config.php)。
完整代码
for folder, subs, files in os.walk(path):
for filename in files:
if filename.endswith('.php'):
phplist.append(abspath(join(folder, filename)))
for i in phplist:
if i.endswith("/config.php"):
cmsconfig.append(i)
if i.endswith("/mdeploy.php"):
cmslist.append(cms1[18])
所以结果只会将/config.php
文件路径添加到列表cmsconfig
但是发生了什么我得到了所有config.php
文件,如上例所示
我一直在使用像is not i.endswith("/theme/brick/config.php")
这样的代码,但我想要一种方法从列表中排除主题目录。
我将输出放入列表的原因是我在代码的另一个区域使用该输出。
答案 0 :(得分:0)
将您的if条件更改为if i.endswith("moodle/config.php")
。
如果您想用以下内容更改您想要的文件夹:
path_ending = '%s/config.php' % folder_name
现在将if条件更改为if i.endswith(path_ending)
这将显示在您传递的文件夹tbat中以config.php
结尾的路径。
答案 1 :(得分:0)
我认为这就是你想要的。可能会改变变量的命名,而不是pep8风格。
首先,我排序最短的所有条目,然后我记得哪些部分已经被检查过。
url1 = '/home/comradec/public_html/moodle/theme/binarius/config.php'
url2 = '/home/comradec/public_html/moodle/config.php'
url3 = '/home/comradec/public_html/othername/theme/binarius/config.php'
url4 = '/home/comradec/public_html/othername/config.php'
urls = []
urls.append(url1)
urls.append(url2)
urls.append(url3)
urls.append(url4)
moodleUrls = []
checkedDirs = []
#sort
for i in sorted(urls):
if str(i).endswith('config.php'):
alreadyChecked = False
for checkedDir in checkedDirs:
if str(i).startswith(checkedDir):
alreadyChecked = True
break
if not alreadyChecked:
moodleUrls.append(i)
checkedDirs.append(str(i).replace('/config.php',''))
print(checkedDirs)
print(moodleUrls)
输出:
['/home/comradec/public_html/moodle', '/home/comradec/public_html/othername']
['/home/comradec/public_html/moodle/config.php', '/home/comradec/public_html/othername/config.php']
答案 2 :(得分:0)
我解决问题的方式。提供我正在寻找的输出。
path = "/home/comradec"
phplist = []
cmsconfig = []
config = "config.php"
for folder, subs, files in os.walk(path):
for filename in files:
if filename.endswith('.php'):
phplist.append(abspath(join(folder, filename)))
for i in phplist:
if i.endswith("/mdeploy.php"):
newurl = i
newurl = newurl[:-11]
newurl = newurl + config
for i in phplist:
if i.endswith("/config.php"):
confirmurl = i
if confirmurl == newurl:
cmsconfig.append(newurl)
print('\n'.join(cmsconfig))