我正在運行以下代碼,並且我想跳過3個文件夾,其名稱分別爲: folder1,folder2,.repository。在Python搜索中跳過目錄
但是,如果某些文件夾不存在,我得到的錯誤:
indentationerror:取消縮進不匹配任何外部縮進級別
如何搜索跳過的文件夾,即使他們不目前沒有得到任何錯誤?在這裏我的代碼:
import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("."):
dirs.remove("folder1")
dirs.remove("folder2")
dirs.remove(".repo")
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file has been modified",p)
------ UPDATE:
import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("/home/temp/"):
dirs.remove("/home/temp/test1")
dirs.remove("/home/temp/test2")
dirs.remove("/home/temp/test3")
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file contains user code modules:-------------> ",p)
這裏輸出:
python /home/temp/test_folder/python_script_4.py
File "/home/temp/test_folder/python_script_4.py", line 12
if "pom.xml" in files:
^
IndentationError: unexpected indent
最後更新--------->
import re
import os
from os.path import join
comment=re.compile(r"<!--\s+\| Start of user code \(user defined modules\)\s+\|-->\s+<!--\s+\| End of user code\s+\|-->", re.MULTILINE)
tag="<module>"
for root, dirs, files in os.walk("/home/dlopez/temp/test_folder/"):
dirs.remove("/home/temp/test_folder/test1")
dirs.remove("/home/temp/test_folder/test2")
dirs.remove("/home/temp/test_folder/test3")
if "pom.xml" in files:
p=join(root, "pom.xml")
print("Checking",p)
with open(p) as f:
s=f.read()
if tag in s and comment.search(s):
print("The following file contains user code modules:-------------> ",p)
而且我的輸出:
python /home/temp/test_folder/python_script_5.py
Traceback (most recent call last):
File "/home/dlopez/temp/test_folder/python_script_5.py", line 8, in <module>
dirs.remove("/home/temp/test_folder/test1")
ValueError: list.remove(x): x not in list
請幫助謝謝! :)
Additonally最近我得到這個錯誤,即使文件夾中存在:IndentationError:預期縮進塊 – user2961008
此錯誤與您的問題無關。你確定縮進在文件中是正確的嗎? – dunder
該錯誤與您的問題無關,錯誤僅與您的縮進相關 – danielfranca