Python:os.walk中的当前目录

9 投票
4 回答
32763 浏览
提问于 2025-04-17 00:23

我需要在一个os.walk的过程中获取当前目录。当只有一个子目录层级时,这个方法能正常工作,但当层级更多时就不行了。请给我一些建议...

[代码]

# AFFECTS everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could affect all your disk files.

import os, glob, arcpy, csv, sys, shutil, datetime
top = r'L:\Raster_Data\Topographic_Maps'
RootOutput = r'L:\Raster_Data\Topographic_Maps'
#FileList = csv.reader(open('FileList.csv'))
SearchString=['Temp_Pol', 'Spatial_Ex']

filecount=0
successcount=0
errorcount=0

print "Working in: "+os.getcwd()

list =[]
f = open(RootOutput+'\\Success_LOG.txt', 'a')
f.write("Log of files Succesfully processed. RESULT of process run @:"+str(datetime.datetime.now())+"\n")
f.close()

#for File in FileList:
for root, dirs, files in os.walk(top, topdown=False):
  #for directory in dirs:
    for file in files:
      #currentPath=os.path.join(root,directory)
      currentPath=os.path.abspath(file)
      os.chdir(currentPath)
      #arcpy.env.workspace = currentPath
      #print os.getcwd()
      lstFCs = glob.glob('*'+SearchString[0]+'*.shp')
      #print lstFCs
      OutPutDir=os.path.abspath(currentPath)
      for fc in lstFCs:
          filecount=filecount+1
          list.append(OutPutDir+"\\"+fc)       

      lstFCs = glob.glob('*'+SearchString[1]+'*.shp')
      #print lstFCs
      for fc in lstFCs:
          OutPutDir=RootOutput+"\\"+directory
          filecount=filecount+1
          list.append(OutPutDir+"\\"+fc)

print 'Merging: ' + str(list)
#arcpy.Merge_management(list, RootOutput+"\\Full_Extent.shp")
print 'Created: '+RootOutput+"\\Full_Extent.shp"
f = open(RootOutput+'\\Success_LOG.txt', 'a')
f.write(str(list)+"\n\n Merged to: "+RootOutput+"\\Full_Extent.shp")
f.close()

所以这个列表应该包含fc和它的完整路径,但实际上只得到了根路径和路径的最后一部分,而中间的目录没有被包含。

谢谢你的建议,

[错误信息]

当前工作目录:L:\Raster_Data\Topographic_Maps 合并: ['L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\ecw\prj_Temp_Polygon_Extent_0.shp', 'L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\ecw\Temp_Polygon_Extent_0.shp', 'L:\Raster_Data\Topographic_Maps\ecw\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SC54\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SC55\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SD54\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SD55\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SE54\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\prj_Temp_Polygon_Extent_0.shp', 'L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\Temp_Polygon_Extent_0.shp', 'L:\Raster_Data\Topographic_Maps\SE55\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SF54\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SF55\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SF56\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SG55\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SG56\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\SH56\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\Tablelands_100K\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\200DPI\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\1M\prj_Temp_Polygon_Extent_0.shp', 'L:\Raster_Data\Topographic_Maps\1M\Temp_Polygon_Extent_0.shp', 'L:\Raster_Data\Topographic_Maps\250K\prj_Temp_Polygon_Extent_1.shp', 'L:\Raster_Data\Topographic_Maps\250K\Temp_Polygon_Extent_1.shp', 'L:\Raster_Data\Topographic_Maps\250K\Spatial_Extent.shp', 'L:\Raster_Data\Topographic_Maps\5M\prj_Temp_Polygon_Extent_2.shp', 'L:\Raster_Data\Topographic_Maps\5M\Temp_Polygon_Extent_2.shp', 'L:\Raster_Data\Topographic_Maps\5M\Spatial_Extent.shp'] 错误追踪 (最近的调用最后): 文件 "L:\Raster_Data\Topographic_Maps\CreateFileList.py",第64行,执行 arcpy.Merge_management(list, RootOutput+"\Full_Extent.shp")
文件 "C:\Program Files\ArcGIS\Desktop10.0\arcpy\arcpy\management.py", 第3124行,执行合并 抛出e 执行错误:执行失败。参数无效。 错误 000732:输入数据集:数据集 L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\ecw\prj_Temp_Polygon_Extent_0.shp;L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\ecw\Temp_Polygon_Extent_0.shp;L:\Raster_Data\Topographic_Maps\ecw\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SC54\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SC55\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SD54\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SD55\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SE54\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\prj_Temp_Polygon_Extent_0.shp;L:\Raster_Data\Topographic_Maps\100K\2010_100K\Map_Sheets_BestResolution\qld_north\SE55\Temp_Polygon_Extent_0.shp;L:\Raster_Data\Topographic_Maps\SE55\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SF54\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SF55\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SF56\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SG55\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SG56\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\SH56\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\Tablelands_100K\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\200DPI\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\1M\prj_Temp_Polygon_Extent_0.shp;L:\Raster_Data\Topographic_Maps\1M\Temp_Polygon_Extent_0.shp;L:\Raster_Data\Topographic_Maps\250K\prj_Temp_Polygon_Extent_1.shp;L:\Raster_Data\Topographic_Maps\250K\Temp_Polygon_Extent_1.shp;L:\Raster_Data\Topographic_Maps\250K\Spatial_Extent.shp;L:\Raster_Data\Topographic_Maps\5M\prj_Temp_Polygon_Extent_2.shp;L:\Raster_Data\Topographic_Maps\5M\Temp_Polygon_Extent_2.shp;L:\Raster_Data\Topographic_Maps\5M\Spatial_Extent.shp 不存在或不受支持 执行失败(合并)。

当前工作目录:L:\Raster_Data\Topographic_Maps 错误追踪(最近的调用最后): 文件 "L:\Raster_Data\Topographic_Maps\CreateFileList.py",第28行,执行 os.chdir(currentPath) Windows错误:[错误 2] 系统找不到指定的文件: 'L:\Raster_Data\Topographic_Maps\ecw\SC54' 目录 'SC54' 目录列表 ['SC54', 'SC55', 'SD54', 'SD55', 'SE54', 'SE55'] os.path.abspath(dirs[0]) 'L:\Raster_Data\Topographic_Maps\ecw\SC54' os.getcwd() 'L:\Raster_Data\Topographic_Maps\ecw' 当前工作目录:L:\Raster_Data\Topographic_Maps 错误追踪(最近的调用最后): 文件 "L:\Raster_Data\Topographic_Maps\CreateFileList.py",第28行,执行 os.chdir(currentPath) Windows错误:[错误 2] 系统找不到指定的文件: 'L:\Raster_Data\Topographic_Maps\7178cp_dd.ers' 文件 '7178cp_dd.ers' os.path.abspath os.path.abspath(file) 'L:\Raster_Data\Topographic_Maps\7178cp_dd.ers'

4 个回答

2

对于某些应用,我们在使用os.walk这个递归调用的时候,总是需要改变当前的工作目录。在这种情况下,我建议像下面这样改变当前的工作目录两次。我想说的是,有些情况是绝对文件路径并不能解决问题的。

from os import listdir
from os.path import isfile, join
import os
import re
# store the location of the top most directory 
top = os.getcwd()

for (dirname, dirs, files) in os.walk(os.getcwd()):        
        for filename in files:
                os.chdir(dirname)
                # add all your operations for the current job in the directory
                # Now go back to the top of the chain
                os.chdir(top)
2

你应该使用

os.path.join(root, file) 

而不是像 os.walk 文档示例中那样简单地使用文件os.walk

顺便提一下,要小心保留的关键字。file 是一个内置函数,list 也是

>>> a = list()
>>> a
[]
>>> list = []
>>> b = list()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
7

谢谢大家,我根据论坛上的建议完成了这个脚本。下面是我写的代码,供有需要的人使用。祝好!

# AFFECTS everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could affect all your disk files.

import os, arcpy, sys, datetime
top = os.getcwd()
RootOutput = top
FileTypes=['shp']
SearchStrings=['Temp_Pol', 'Spatial_Ex']

filecount=0
#successcount=0
#errorcount=0

print "Working in: "+os.getcwd()

list =[]
f = open(RootOutput+'\\Success_LOG.txt', 'a')
f.write("Log of files Succesfully processed. RESULT of process run @:"+str(datetime.datetime.now())+"\n")
f.close()

for root, dirs, files in os.walk(top, topdown=False):
    for fl in files:
      currentFile=os.path.join(root, fl)
      for FileType in FileTypes:
          status= str.endswith(currentFile,FileType)
          if str(status) == 'True':
              for SearchString in SearchStrings:
                  if str(SearchString in currentFile) == 'True':
                    #print str(currentFile)+str(status)       
                    filecount=filecount+1
                    list.append(currentFile)

print 'Merging: ' + str(list)

#你可以在这里替换成任何你想对生成的文件列表执行的功能。 #arcpy.Merge_management(list, RootOutput+"\Full_Extent.shp")

print 'Created: '+RootOutput+"\\Full_Extent.shp"
f = open(RootOutput+'\\Success_LOG.txt', 'a')
f.write(str(list)+"\n\n Merged to: "+RootOutput+"\\Full_Extent.shp")
f.close()

撰写回答