打开文件并匹配工程师实验室

2024-09-30 05:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

1.从buildlocation获取buildid,该buildlocation位于“\”之后的最后一个字,在本例中为“A1234ABCDE120083.1”

2.在获得buildid之后,我打开一个文件,然后尝试匹配行“Engr Label:Data\u CRM\u PL\u 177999”以获得标签名,即“Data\u CRM\u PL\u 177999”

3.最终输出应为“数据\客户关系\产品\ 177999”

由于某些原因,我得到以下语法错误

 import re

 Buildlocation= '\\umor\locations455\INT\A1234ABCDE120083.1'

 Labelgetbuildlabel(Buildlocation)

def getbuildlabel(BuildLocation):
buildid=BuildLocation.split('\')[-1]
Notes=os.path.join(BuildLocation,Buildid + '_notes.txt')
if os.path.exists(Notes):
    try:
        open(Notes)
    except IOError as er:
        pass
    else:
        for i in Notes.splitlines:
        if i.find(Engr Label)
            label=i.split(:)[-1]

print label//output should be Data_CRM_PL_177999

输出应为:-

Line looks like below in the file
Engr Label: Data_CRM_PL_177999

语法错误

 buildid=BuildLocation.split('\')[-1]
                                   ^
 SyntaxError: EOL while scanning string literal

Tags: pathdataifoslabelnotessplitpl
2条回答

反斜杠转义'字符(请参见escape codes documentation

请改用这句话:

 buildid=BuildLocation.split('\\')[-1]    

现在有一个反斜杠转义为反斜杠,所以字符串是一个字面上的反斜杠。您可以做的另一件事是告诉Python这个字符串没有任何转义码,方法是在它前面加上r,如下所示:

 buildid=BuildLocation.split(r'\')[-1]   

你还有很多其他的问题

Python中的注释字符是#,而不是//

我想你也把文件名和文件对象搞混了

Notes是您试图打开的文件的名称。然后,当您调用open(Notes)时,您将得到一个可以从中读取数据的文件对象

所以你应该替换:

open(Notes)

f = open(Notes)

然后替换:

for i in Notes.splitlines:

for line in f:

当您对文件对象执行for循环时,Python会自动一次给出一行

现在你可以这样检查每一行:

if line.find("Engr Label") != -1:
  label = line.split(':')[-1]

排队

buildid=BuildLocation.split('\')[-1]

反斜杠实际上是在转义下面的引号 所以,Python认为这实际上是你的字符串:

'[-1])

相反,您应该执行以下操作:

buildid=BuildLocation.split('\\')[-1]

Python会将字符串解释为

\\

有趣的是,StackOverflow的语法highlighter提示了这个问题。如果查看代码,它会将第一个斜杠之后的所有内容都视为字符串的一部分,一直到代码示例的结尾

你的代码中还有一些其他问题,所以我试着帮你清理一下(但是,我没有该文件的副本,所以很明显,我无法测试这个)

import re
import os.path

build_location= r'\\umor\locations455\INT\A1234ABCDE120083.1'


label = get_build_label(build_location)

# Python prefers function and variable names to be all lowercase with
# underscore separating words.
def get_build_label(build_location):
    build_id = build_location.split('\\')[-1]
    notes_path = os.path.join(build_location, build_id + '_notes.txt')
    # notes_path is the filename (a string)
    try:
        with open(notes_path) as notes:
            # The 'with' keyword will automatically open and close
            # the file for you
            for line in notes:
                if line.find('Engr Label'):
                    label = line.split(':')[-1]
                    return label
    except IOError:
        # No need to do 'os.path.exists' since notes_path doesn't
        # exist, then the IOError exception will be raised.
        pass
print label

相关问题 更多 >

    热门问题