Movatterモバイル変換


[0]ホーム

URL:


[Tutor] Escaping globs for glob.iglob()

Ray Jonescrawlzone at gmail.com
Tue Aug 21 08:15:30 CEST 2012


On 08/20/2012 11:05 PM, Peter Otten wrote:> Ray Jones wrote:>>> The code:>>>>   curDir = os.getcwd()>>   znDir = shutil.abspath('../')>>   baseDir = shutil.abspath('../../')>>>>   Files = glob.iglob(os.path.join(znDir, '*'))>>   print Files>>>>   for moveFile in Files:>>     print moveFile>>     shutil.move(moveFile, curDir)>>>> Nothing happens. The 'print...moveFile' never happens, even though print>> Files shows it to be an iglob generator object.>>>> After reading over the glob docs and working the directories backward>> manually, I realized that one of the directory names in the znDir path>> begins with '[1st]'. According to the docs, glob is apparently seeing>> that as a character range. No problem, I'll simply escape the '[' and>> ']' with backslashes.  I used:>>>> znDir = znDir.replace('[', '\[')>> and then>> znDir = znDir.replace(']', '\]')>>>> No such luck. Glob still does not recognize the file glob in znDir/*.>> Later in the code I will be using creating symbolic links, and I wish to>> use the absolute path rather than the relative path.>>>> Any idea of how to sanitize this path so that I can get glob to work?> Try>> znDir = znDir.replace("[", "[[]")That never occurred to me. Excellent.> Alternatively use os.listdir(znDir):>> [os.path.join(znDir, name) for name in os.listdir(znDir)]I've actually used this similarly in the past. I don't know why I gothung up on glob! ;)> For a non-trivial file pattern:>> pattern = "*tmp*.py"> files = [os.path.join(znDir, name) for name in>  fnmatch.filter(os.listdir(znDir), pattern)]I looked at fnmatch.filter and didn't see how I could use it in thisinstance - it's crystal clear now.Thanks for the help. I think it's going to work now!Ray


More information about the Tutormailing list

[8]ページ先頭

©2009-2026 Movatter.jp