[英]Python - How do you read multiple files in a folder starting by xyz?
[英]python read all files in a folder except a file named “xyz”
我想讀取文件夾中除名為“ xyz”的文件以外的所有文件。 當我到達此文件時,我想跳過它並閱讀下一個文件。
目前,我有以下代碼:
for file in glob.glob('*.xml'):
data = open(file).read()
print(file)
顯然,這將讀取該文件夾中的所有文件。 我應該如何跳過文件“ xyz.xml”
continue
關鍵字對於跳過for循環的迭代很有用:
for file in glob.glob('*.xml'):
if file=="xyz.xml":
continue
data = open(file).read()
print(file)
for file in [f for f in glob.glob('*.xml') if f != "xyz.xml"]:
do_stuff()
嘗試執行此操作,假設要刪除的元素在glob.glob()
返回的列表中(如果不能保證,請將remove()
行放在try
塊中):
lst = glob.glob('*.xml')
lst.remove('xyz.xml') # assuming that the element is present in the list
for file in lst:
pass
或者,如果您關心內存使用情況,請使用生成器:
for file in (file for file in glob.glob('*.xml') if file != 'xyz.xml'):
pass
為了完整起見,沒有人發布最明顯的版本:
for file in glob.glob('*.xml'):
if file != 'xyz.xml':
data = open(file).read()
print(file)
您可以使用glob進行非常簡單的模式匹配,但請記住,glob的模式規則不是正則表達式! 以下代碼可以幫助您排除以'X'開頭的所有xml文件
files = glob.glob('[!X]*.xml')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.