[英]python read all files in a folder except a file named “xyz”
I want to read all files in a folder except a file named "xyz". 我想读取文件夹中除名为“ xyz”的文件以外的所有文件。 When I reach to this file, I want to skip it and read the next one.
当我到达此文件时,我想跳过它并阅读下一个文件。
Currently I have the following code: 目前,我有以下代码:
for file in glob.glob('*.xml'):
data = open(file).read()
print(file)
Obviously, this will read all files in that folder. 显然,这将读取该文件夹中的所有文件。 How should I skip the file "xyz.xml"
我应该如何跳过文件“ xyz.xml”
The continue
keyword is useful for skipping an iteration of a for loop: 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()
Try this, assuming that the element to be removed is in the list returned by glob.glob()
(if that's not guaranteed, put the remove()
line inside a try
block): 尝试执行此操作,假设要删除的元素在
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
Or if you care about memory usage, use a generator: 或者,如果您关心内存使用情况,请使用生成器:
for file in (file for file in glob.glob('*.xml') if file != 'xyz.xml'):
pass
For sake of completeness as no one posted the most obvious version: 为了完整起见,没有人发布最明显的版本:
for file in glob.glob('*.xml'):
if file != 'xyz.xml':
data = open(file).read()
print(file)
You can use glob for fairly simple pattern matching but remember that pattern rules for glob are not regular expressions! 您可以使用glob进行非常简单的模式匹配,但请记住,glob的模式规则不是正则表达式! Below code can help you exclude all xml files that start with 'X'
以下代码可以帮助您排除以'X'开头的所有xml文件
files = glob.glob('[!X]*.xml')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.