我是一个蟒蛇新手并且遇到以下问题。如果我取消注释此代码的最后一行:
# traverse all directories
for root, dirs, files in os.walk(args.rootfolder):
for file in files:
print('Current file name: ' + file)
if file.endswith('.savx'):
# read single xml savx file
currfilename = os.path.join(root,file)
print('Current full file name: ' + currfilename)
tree = ET.parse(currfilename)
# root = tree.getroot() <-- if I uncomment this line I get errors
我收到此错误:
Traceback (most recent call last):
File "convert.py", line 30, in <module>
currfilename = os.path.join(root,file)
File "C:\progs\develop\Python34\lib\ntpath.py", line 108, in join
result_drive, result_path = splitdrive(path)
File "C:\progs\develop\Python34\lib\ntpath.py", line 161, in splitdrive
normp = p.replace(_get_altsep(p), sep)
AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'replace'
看起来错误出现在第二次file in files
循环迭代之后。
答案 0 :(得分:3)
您在代码中使用root
两次,用于不同的事情:
for root, dirs, files in os.walk(args.rootfolder):
# ^^^^
和
root = tree.getroot()
因此,在构建要加载的下一个文件名时,尝试使用root
作为路径字符串:
currfilename = os.path.join(root,file)
您会发现您使用ElementTree对象替换了root
路径名称。
为根目录名称或ElementTree对象使用不同的名称。例如,使用dirname
:
for dirname, dirs, files in os.walk(args.rootfolder):
for file in files:
print('Current file name: ' + file)
if file.endswith('.savx'):
# read single xml savx file
currfilename = os.path.join(dirname, file)
print('Current full file name: ' + currfilename)
tree = ET.parse(currfilename)
root = tree.getroot()