在Python中循环遍历文件目录 [英] Looping through a directory of files in Python

查看:61
本文介绍了在Python中循环遍历文件目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的第一个python脚本已经完成了99%的工作,但我陷入了遍历目录文件中的for-each循环的困境.我的脚本适用于单个文件,但我不确定如何一次将其应用于多个文件.

I'm 99% of the way through my first python script, but I'm getting tripped up on the equivalent of a for-each loop through files in a directory. My script is working for single files, I'm just not sure how to apply it to multiple files, one at a time.

我有一个路径 path =〜/documents 和一个带有我想排除的文件名的XML文件:

I have a path path = ~/documents and an XML file with filenames I would like to exclude:

 <root><synced name="Already Synced"><sfile name="Filename">base</sfile><sfile name="Filename">File1.blah</sfile><sfile name="Filename">File2.blah</sfile><sfile name="Filename">File3.blah</sfile></synced></root>

我将如何在所有以 *.blah 结尾且不在XML sfile中的文件上运行脚本?

how would I run my script on, say, all files that end with *.blah and are NOT in the XML sfile?

我有这个,但这是不行的:

I had this, but it was a no-go:

path = '~/documents'
tree = ET.parse("sync_list.xml")
root = tree.getroot()
for elem in root.findall('sfile'):
    synced = elem.text
do_library = os.listdir(path)
if glob.fnmatch.fnmatch(file,"*.blah") and not synced:
  for entry in do_library:
    file = os.path.join(path, entry)
    result = plistlib.readPlist('file')

非常感谢您能提供的任何帮助.

Thank you so much for any help you can offer.

推荐答案

import fnmatch
import os

path = os.path.expanduser('~/documents')
tree = ET.parse("sync_list.xml")
root = tree.getroot()
synced = [elt.text for elt in root.findall('synced/sfile')]
for filename in os.listdir(path):
    if fnmatch.fnmatch(filename, '*.blah') and filename not in synced:
        filename = os.path.join(path, filename)

按照@mata的建议,添加了os.path.expanduser.

Added os.path.expanduser, as suggested by @mata.

这篇关于在Python中循环遍历文件目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆