Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取和更新pycharm中的XML,但不在命令行中_Python_Xml_Encoding_Pycharm_Python 3.6 - Fatal编程技术网

Python 读取和更新pycharm中的XML,但不在命令行中

Python 读取和更新pycharm中的XML,但不在命令行中,python,xml,encoding,pycharm,python-3.6,Python,Xml,Encoding,Pycharm,Python 3.6,我对python非常陌生,所以。该脚本将打开文件夹中的xml文件。我使用os.walk遍历集合并打开文件,然后调用函数遍历xml文件并更新xml文件,使用.writexml在原始集合上重写更新的文件。问题是当我从命令行运行这个程序时,它说有一个错误 Traceback (most recent call last): File "./XMLParser.py", line 67, in <module> xmldoc = minidom.parse(xml) File

我对python非常陌生,所以。该脚本将打开文件夹中的xml文件。我使用os.walk遍历集合并打开文件,然后调用函数遍历xml文件并更新xml文件,使用.writexml在原始集合上重写更新的文件。问题是当我从命令行运行这个程序时,它说有一个错误

Traceback (most recent call last):
  File "./XMLParser.py", line 67, in <module>
    xmldoc = minidom.parse(xml)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 1918, in parse
    return expatbuilder.parse(file)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 928, in parse
    result = builder.parseFile(file)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 207, in parseFile
    parser.Parse(buffer, 0)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 5614: ordinal not in range(128)
回溯(最近一次呼叫最后一次):
文件“/XMLParser.py”,第67行,在
xmldoc=minidom.parse(xml)
parse中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py”,第1918行
返回expatbuilder.parse(文件)
parse中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py”,第928行
结果=builder.parseFile(文件)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py”,第207行,在parseFile中
parser.Parse(缓冲区,0)
UnicodeEncodeError:“ascii”编解码器无法对5614位置的字符u'\xa0'进行编码:序号不在范围内(128)
代码:

从xml.dom导入minidom
导入操作系统
导入编解码器
'''
函数来迭代包含工作项的目录
参数:
新作者科雷德,
x是workItem.xml文件的路径,
p是将被新数据覆盖的workItem.xml的路径
'''
def changeauthor(coreid,x,p):
#获取工作项标记中基于xml的内容。
testcase=x.getElementsByTagName(“工作项”)[0]
#所有字段都存储为标记,id属性为
#它们之间的区别。字段是列表中所有字段标记的列表
#文件。
fields=testcase.getElementsByTagName(“字段”)
#循环遍历字段标记并查找id所在的一个标记
#属性的值为author。找到此标记时,标记值为
#更新为传递给函数的核心id。
对于字段中的字段:
attribute=field.attributes['id'].value
如果属性==“作者”:
#打印当前作者。
打印(“上一个作者:”,field.firstChild.data)
#将作者设置为脚本中输入的核心id
field.firstChild.data=coreid
#打印更新的作者字段
打印(“新作者:”,field.firstChild.data)
#创建与源路径相同的临时文件
tmp_config=p
#打开设置了写入模式的新临时文件。
使用codecdes.open(tmp_config,'w','utf-8')作为f:
#f=打开(tmp_配置“w”)
#将xml写入与原始文件位于同一位置的文件中
x、 writexml(f)
#关闭文件
#f.关闭()
返回
尽管如此:
core=str(输入(“输入新作者的核心ID:”)
core=core.upper()
spath=str(输入(“请输入测试用例目录的完整路径:”)
计数=0
确认=str(输入(“确认路径和核心id(是/否或退出以离开脚本):”)
confirm=confirm.upper()
如果确认==“Y”:
''这里的硬代码路径和上面的注释行请求输入两者都可以工作''
#spath=“/Users/Evan/Desktop/workitems-r583233”
#循环在目录上迭代。每当找到workitem.xml文件时,都会存储路径并保存该文件
#解析。输入的核心ID、路径以及解析的xml文档将传递给变更作者
#功能。
对于os.walk(spath)中的根、目录和文件:
对于文件中的文件:
title=file.title()
如果title==“Workitem.Xml”:
path=os.path.join(根,文件)
使用codecs.open(路径“r+”,“utf-8”)作为xml:
xmldoc=minidom.parse(xml)
lst=path.split(“/”)
wi=lst[5]
打印(“更新:”,wi)
changeauthor(核心、xmldoc、路径)
计数+=1
打印(wi,“已成功更新”)
打印(-------------------------------------)
如果计数>0:
#打印更新了多少测试用例。
打印(“全部完成”,计数,“工作项已更新!”)
其他:
打印(“请仔细检查路径并重试,未找到要更新的工作项!”)
elif确认==“N”:
持续
elif确认==“退出”:
打破

是否应该将文件作为普通文件打开,然后使用mini-dom parse string方法解析每一行?是的,只需将
path
直接发送到
minidom.parse()
,而无需打开文件。如果它再次出现字符错误,则将文件作为字符串对象打开,对其进行编码和解码,然后将其作为字符串传递给
minidom.parseString()
。我是否仍然能够使用writexml方法在原始文件上写入文件?
from xml.dom import minidom

import os

import codecs

'''
Function to iterate over the directory that contains the work items
params:
    CoreID of new author,
    x is the path to the workItem.xml file,
    p is the path to the workItem.xml that will be overwritten with new data
'''
def changeauthor(coreid, x, p):
# Gets the content of the xml based within the work item tag.
testcase = x.getElementsByTagName("work-item")[0]

# All fields are stored as a <field> tag with the id attribute being the
# differentiators between them. Fields is a list of all the field tags in the
# document.
fields = testcase.getElementsByTagName("field")

# Loop iterates over the field tags and looks for the one tag where the id
# attribute has a value of author. when this tag is found the tags value is
# updated to the core id passed to the function.
for field in fields:
    attribute = field.attributes['id'].value
    if attribute == "author":
        # print the current author.
        print("Previous Author: ", field.firstChild.data)
        # Set the author to the core id entered into the script
        field.firstChild.data = coreid
        # Print the updated author field
        print("New Author: ", field.firstChild.data)
        # Create a temp file with the same path as the source
        tmp_config = p
        # Open the new temp file with the write mode set.
        with codecs.open(tmp_config, 'w', "utf-8") as f:
        # f = open(tmp_config, 'w')
        # Write the xml into the file at the same location as the orginal
            x.writexml(f)
        # Close the file
        # f.close()

return


while True:
    core = str(input("Enter Core ID of the new author: "))
    core = core.upper()
    spath = str(input("Please enter the full path to the directory of test cases: "))
    count = 0
    confirm = str(input("Confirm path and core id (Y/N or Exit to leave script): "))
    confirm = confirm.upper()
    if confirm == "Y":
        '''Hard code path here and comment out line above asking for input either will work.'''
        # spath = "/Users/Evan/Desktop/workitems-r583233"

        # Loop iterates over the directory. Whenever a workitem.xml file is found the path is stored and the file is
        # parsed. the core ID entered and the path as well as the parsed xml doc are passed to the change author
        # function.
        for roots, dirs, files in os.walk(spath):
            for file in files:
                title = file.title()
                if title == "Workitem.Xml":
                    path = os.path.join(roots, file)
                    with codecs.open(path, 'r+', "utf-8") as xml:
                        xmldoc = minidom.parse(xml)
                    lst = path.split('/')
                    wi = lst[5]
                    print("Updating: ", wi)
                    changeauthor(core, xmldoc, path)
                    count += 1
                    print(wi, "updated succesfully.")
                    print("-------------------------------")
        if count > 0:
            # Print how many test cases were updated.
            print("All Done", count, "workItems updated!")
        else:
            print("Please double check path and try again no workItems found to update!")
   elif confirm == "N":
       continue
   elif confirm == "EXIT":
       break