简体   繁体   中英

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". 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"

The continue keyword is useful for skipping an iteration of a for loop:

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):

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! Below code can help you exclude all xml files that start with 'X'

files = glob.glob('[!X]*.xml')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM