首页 > 解决方案 > 如何比较字符串中特定位置的字符来识别处理路径

问题描述

我试图确定 .txt/string 中的第一个字符是“{”还是“<”。取决于哪个将决定如何处理 .txt。

我正在使用两个系统,一个采用 xml,另一个采用 json。因此,当文件来自一个系统时,它会被转换并发送到另一个系统。如果文件具有正确的文件扩展名,我已经计算出文件的转换,但现在我需要能够根据 .txt 文件的内容识别文件是 json 还是 xml。我不知道为什么会发生这种情况,但被要求包括在内。

据我所知,最好的方法是基于文件中的第一个字符。如果它是“<”而不是 xml,如果它是“{”而不是 json。我不知道仅在 json 中或仅在 xml 中的字符,我可以通过这种方式搜索和识别。

# txt to xml and json 下面的代码正在整个文件中搜索可能给出误报的字符串,这就是我试图只查看第一个字符的原因。

start_path = 'fileLocation'
for path,dirs,files in os.walk(start_path):
    for fileName in files:
        filePath = os.path.join(path,fileName)

        # xml2json
        if re.match('.*\.xml',fileName):
            with open(filePath) as x:
                xStr = x.read()
            jStr = json.dumps(xmltodict.parse(xStr), indent=4)
            with open("jsonOutput.json", 'w') as j:
                j.write(jStr)

        # json2xml
        elif re.match('.*\.json',fileName):
            with open(filePath) as j:
                jStr = j.read()
            xStr = xmltodict.unparse(json.loads(jStr), pretty=True)
            with open('xmlOutput.xml', 'w') as x:
                x.write(xStr)

        # **Where I'm Having Trouble**
        # txt to xml and json
        elif re.match('.*\.txt',fileName):
            with open(filePath) as t:
                tStr = t.read()
                if 'xml' in tStr:
                    with open('xmlOutput.xml', 'w') as x:
                        x.write(tStr)
                elif '{' in tStr:
                    with open('jsonOutput.xml', 'w') as j:
                        j.write(tStr)

理想的解决方案是将 'xml' 和 '{' 完整的 txt 搜索替换为 '<' 和 '{' 检查第一个字符。

任何帮助都非常感谢,谢谢。

标签: jsonxmlpython-3.xstring

解决方案


如果有人感兴趣,我找到了使用 readline() 的解决方案。这仅读取第一行,如果找到'{',它将作为json处理,如果有'<',它将作为xml处理。感谢大家的帮助。

# unk to json & xml
        else:
            with open(filePath) as u:
                fLine = u.readline() #This is only reading the first line.
                uStr = u.read()
            if '<' in fLine:
                time = strftime('%Y%b%d %H%M', gmtime())
                fName = fileName + ' ' + time + ".xml"
                with open(fName, 'w') as x:
                    x.write(uStr)
            elif '{' in fLine:
                time = strftime('%Y%b%d %H%M', gmtime())
                fName = fileName + ' ' + time + ".json"
                with open(fName, 'w') as j:
                    j.write(uStr)

推荐阅读