AttributeError: __len__ ntpath.py 和 Tkinter.py 错误

发布于 2025-01-01 05:27:51 字数 5460 浏览 0 评论 0原文

当我运行脚本并且它正在更改目录时出现以下错误 - 如何修复此错误?

回溯(最近一次调用最后一次):文件 “L:\ Data_Admin \ QA \ Metadata_python_toolset \ test2 \ update_Metadata1e.py”, 17号线,在 currentPath=os.path.join(root,directory) 文件“C:\Python26\ArcGIS10.0\lib\ntpath.py”,第 96 行,在 join 中 断言 len(路径) > 0 文件“C:\Python26\ArcGIS10.0\lib\lib-tk\Tkinter.py”,第 1722 行,位于 获取属性 返回 getattr(self.tk, attr) AttributeError: len

完整代码

import os, xml, arcpy, shutil, datetime, Tkinter,tkFileDialog
from xml.etree import ElementTree as et 

path=os.getcwd()
RootDirectory=path
arcpy.env.workspace = path
Count=0

Generated_XMLs=RootDirectory+'\GeneratedXML_LOG.txt'
f = open(Generated_XMLs, 'a')
f.write("Log of Metadata Creation Process - Update: "+str(datetime.datetime.now())+"\n")
f.close()

for root, dirs, files in os.walk(RootDirectory, topdown=False):
    #print root, dirs
    for directory in dirs:
        currentPath=os.path.join(root,directory)
        os.chdir(currentPath)
        arcpy.env.workspace = currentPath
        print currentPath
#def Create_xml(currentPath):

        FileList = arcpy.ListFeatureClasses()
        zone="_Zone"

        for File in FileList:
            Count+=1
            FileDesc_obj = arcpy.Describe(File)
            FileNm=FileDesc_obj.file
            check_meta=os.listdir(currentPath)
            existingXML=FileNm[:FileNm.find('.')]
            existingExtension=FileNm[FileNm.find('.'):]
            print "XML: "+existingXML
            #print check_meta
            #if  existingXML+'.xml' in check_meta:
            #newMetaFile='new'
            for f in check_meta:
                if f.startswith(existingXML) and f.endswith('.xml'):
                    print "exists, file name:", f
                    newMetaFile=FileNm+"_2012Metadata.xml"
                    shutil.copy2(f, newMetaFile)
                    break
                else:
                    #print "Does not exist"
                    newMetaFile=FileNm+"_BaseMetadata.xml"

            print "New meta file: "+newMetaFile+ " for: "+File
            if newMetaFile.endswith('_BaseMetadata.xml'):        
                print "calling tkinter"
                root = Tkinter.Tk()
                file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a xml base file to match with: '+File)
                if file != None:
                    metafile=os.path.abspath(file.name)
                    file.close()
                    #print metafile
                    shutil.copy2(metafile,newMetaFile)
                    print "copied"+metafile
                    root.destroy

                else:
                    shutil.copy2('L:\Data_Admin\QA\Metadata_python_toolset\Master_Metadata.xml', newMetaFile)


            print "Parsing meta file: "+newMetaFile
            tree=et.parse(newMetaFile)        
            print "Processing: "+str(File)

            for node in tree.findall('.//title'):
                node.text = str(FileNm)
            for node in tree.findall('.//northbc'):
                node.text = str(FileDesc_obj.extent.YMax)
            for node in tree.findall('.//southbc'):
                node.text = str(FileDesc_obj.extent.YMin)
            for node in tree.findall('.//westbc'):
                node.text = str(FileDesc_obj.extent.XMin)
            for node in tree.findall('.//eastbc'):
                node.text = str(FileDesc_obj.extent.XMax)        
            for node in tree.findall('.//native/nondig/formname'):
                node.text = str(os.getcwd()+"\\"+File)
            for node in tree.findall('.//native/digform/formname'):
                node.text = str(FileDesc_obj.featureType)
            for node in tree.findall('.//avlform/nondig/formname'):
                node.text = str(FileDesc_obj.extension)
            for node in tree.findall('.//avlform/digform/formname'):
                node.text = str(float(os.path.getsize(File))/int(1024))+" KB"
            for node in tree.findall('.//theme'):
                node.text = str(FileDesc_obj.spatialReference.name +" ; EPSG: "+str(FileDesc_obj.spatialReference.factoryCode))
            print node.text
            projection_info=[]
            Zone=FileDesc_obj.spatialReference.name

            if "GCS" in str(FileDesc_obj.spatialReference.name):
                projection_info=[FileDesc_obj.spatialReference.GCSName, FileDesc_obj.spatialReference.angularUnitName, FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName]
                print "Geographic Coordinate system"
            else:
                projection_info=[FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName, FileDesc_obj.spatialReference.angularUnitName, Zone[Zone.rfind(zone)-3:]]
                print "Projected Coordinate system"
            x=0
            for node in tree.findall('.//spdom'):
                for node2 in node.findall('.//keyword'):
                    print node2.text
                    node2.text = str(projection_info[x])
                    print node2.text
                    x=x+1


            tree.write(newMetaFile)

            f = open(Generated_XMLs, 'a')
            f.write(str(Count)+": "+File+"; "+newMetaFile+"; "+currentPath+"\n")
            f.close()

        print "change dir 1"
    print "change dir 2"


    #        Create_xml(currentPath)

I get the following error when I run a script and it's changing the directory - how can I bug fix this?

Traceback (most recent call last): File
"L:\Data_Admin\QA\Metadata_python_toolset\test2\update_Metadata1e.py",
line 17, in
currentPath=os.path.join(root,directory) File "C:\Python26\ArcGIS10.0\lib\ntpath.py", line 96, in join
assert len(path) > 0 File "C:\Python26\ArcGIS10.0\lib\lib-tk\Tkinter.py", line 1722, in
getattr
return getattr(self.tk, attr) AttributeError: len

Full code

import os, xml, arcpy, shutil, datetime, Tkinter,tkFileDialog
from xml.etree import ElementTree as et 

path=os.getcwd()
RootDirectory=path
arcpy.env.workspace = path
Count=0

Generated_XMLs=RootDirectory+'\GeneratedXML_LOG.txt'
f = open(Generated_XMLs, 'a')
f.write("Log of Metadata Creation Process - Update: "+str(datetime.datetime.now())+"\n")
f.close()

for root, dirs, files in os.walk(RootDirectory, topdown=False):
    #print root, dirs
    for directory in dirs:
        currentPath=os.path.join(root,directory)
        os.chdir(currentPath)
        arcpy.env.workspace = currentPath
        print currentPath
#def Create_xml(currentPath):

        FileList = arcpy.ListFeatureClasses()
        zone="_Zone"

        for File in FileList:
            Count+=1
            FileDesc_obj = arcpy.Describe(File)
            FileNm=FileDesc_obj.file
            check_meta=os.listdir(currentPath)
            existingXML=FileNm[:FileNm.find('.')]
            existingExtension=FileNm[FileNm.find('.'):]
            print "XML: "+existingXML
            #print check_meta
            #if  existingXML+'.xml' in check_meta:
            #newMetaFile='new'
            for f in check_meta:
                if f.startswith(existingXML) and f.endswith('.xml'):
                    print "exists, file name:", f
                    newMetaFile=FileNm+"_2012Metadata.xml"
                    shutil.copy2(f, newMetaFile)
                    break
                else:
                    #print "Does not exist"
                    newMetaFile=FileNm+"_BaseMetadata.xml"

            print "New meta file: "+newMetaFile+ " for: "+File
            if newMetaFile.endswith('_BaseMetadata.xml'):        
                print "calling tkinter"
                root = Tkinter.Tk()
                file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a xml base file to match with: '+File)
                if file != None:
                    metafile=os.path.abspath(file.name)
                    file.close()
                    #print metafile
                    shutil.copy2(metafile,newMetaFile)
                    print "copied"+metafile
                    root.destroy

                else:
                    shutil.copy2('L:\Data_Admin\QA\Metadata_python_toolset\Master_Metadata.xml', newMetaFile)


            print "Parsing meta file: "+newMetaFile
            tree=et.parse(newMetaFile)        
            print "Processing: "+str(File)

            for node in tree.findall('.//title'):
                node.text = str(FileNm)
            for node in tree.findall('.//northbc'):
                node.text = str(FileDesc_obj.extent.YMax)
            for node in tree.findall('.//southbc'):
                node.text = str(FileDesc_obj.extent.YMin)
            for node in tree.findall('.//westbc'):
                node.text = str(FileDesc_obj.extent.XMin)
            for node in tree.findall('.//eastbc'):
                node.text = str(FileDesc_obj.extent.XMax)        
            for node in tree.findall('.//native/nondig/formname'):
                node.text = str(os.getcwd()+"\\"+File)
            for node in tree.findall('.//native/digform/formname'):
                node.text = str(FileDesc_obj.featureType)
            for node in tree.findall('.//avlform/nondig/formname'):
                node.text = str(FileDesc_obj.extension)
            for node in tree.findall('.//avlform/digform/formname'):
                node.text = str(float(os.path.getsize(File))/int(1024))+" KB"
            for node in tree.findall('.//theme'):
                node.text = str(FileDesc_obj.spatialReference.name +" ; EPSG: "+str(FileDesc_obj.spatialReference.factoryCode))
            print node.text
            projection_info=[]
            Zone=FileDesc_obj.spatialReference.name

            if "GCS" in str(FileDesc_obj.spatialReference.name):
                projection_info=[FileDesc_obj.spatialReference.GCSName, FileDesc_obj.spatialReference.angularUnitName, FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName]
                print "Geographic Coordinate system"
            else:
                projection_info=[FileDesc_obj.spatialReference.datumName, FileDesc_obj.spatialReference.spheroidName, FileDesc_obj.spatialReference.angularUnitName, Zone[Zone.rfind(zone)-3:]]
                print "Projected Coordinate system"
            x=0
            for node in tree.findall('.//spdom'):
                for node2 in node.findall('.//keyword'):
                    print node2.text
                    node2.text = str(projection_info[x])
                    print node2.text
                    x=x+1


            tree.write(newMetaFile)

            f = open(Generated_XMLs, 'a')
            f.write(str(Count)+": "+File+"; "+newMetaFile+"; "+currentPath+"\n")
            f.close()

        print "change dir 1"
    print "change dir 2"


    #        Create_xml(currentPath)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰魂雪魄 2025-01-08 05:27:51

您的 os.chdir 可能会混淆 os.walk。尝试在下一次迭代之前恢复工作目录。

更好的是,如果您为 chdir 定义了上下文管理器,则可以使用 with 语句。 这是一个示例,它定义了 chdir 您可以按如下方式使用:

  for root, dirs, files in os.walk(RootDirectory, topdown=False):
    for directory in dirs:
      currentPath=os.path.join(root,directory)
      with chdir(currentPath):
        # now inside the specified directory
        # after exiting 'with', original directory will be restored

It's possible that your os.chdir is confusing os.walk. Try restoring the working directory before the next iteration.

Better yet, you can use a with statement if you define a context manager for chdir. Here's an example, which defines a version of chdir that you can use as follows:

  for root, dirs, files in os.walk(RootDirectory, topdown=False):
    for directory in dirs:
      currentPath=os.path.join(root,directory)
      with chdir(currentPath):
        # now inside the specified directory
        # after exiting 'with', original directory will be restored

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文