在Python中格式化文本文件中的路径以供使用

2024-10-01 00:29:15 发布

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

我正在编写一个Python脚本,供多个非Python用户使用。 我有一个包含脚本需要运行的参数的文本文件

其中一个输入是路径。我无法运行我的脚本,并认为这是因为我引用了我的路径不正确

我试过:

C:\temp\test
"C:\temp\test"
r"C:\temp\test"
C:/temp/test
"C:/temp/test"
C:\\temp\\test
"C:\\temp\\test"

我已经将其中的每一个添加到一个文本文件中,在我的Python脚本中调用并读取该文件。 我有其他参数,它们被正确调用,我的脚本似乎运行时,我硬代码的路径。我说似乎是因为我认为有一些错误,我需要检查,但它运行没有错误

当我使用文本文件时,会出现此错误-这取决于我是否使用了上述示例之一:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'c:\temp\match1\jpg\n/.'

我的代码如下:

print ("Linking new attachments to feature")    
fp = open(r"C:\temp\Match1\Match_Table.txt","r") #reads my text file with inputs

lines=fp.readlines()

InFeat = lines[1]
print (InFeat) 

AttFolder = lines[3] #reads the folder from the text file
print (AttFolder)

OutTable = lines[5] 
if arcpy.Exists(OutTable):
    print("Table Exists")
    arcpy.Delete_management(OutTable)

OutTable = lines[5]
print (OutTable)

LinkF = lines[7]
print (LinkF)
fp.close()


#adding from https://community.esri.com/thread/90280

if arcpy.Exists("in_memory\\matchtable"):
    arcpy.Delete_management("in_memory\\matchtable")
print ("CK Done")
input = InFeat
inputField = "OBJECTID"

matchTable = arcpy.CreateTable_management("in_memory", "matchtable")
matchField = "MatchID"
pathField = "Filename"
print ("Table Created")
arcpy.AddField_management(matchTable, matchField, "TEXT")
arcpy.AddField_management(matchTable, pathField, "TEXT")


picFolder = r"C:\temp\match1\JPG" #hard coded in


print (picFolder)

print ("Fields added")

fields = ["MatchID", "Filename"]
cursor = arcpy.da.InsertCursor(matchTable, fields)
  ##go thru the picFolder of .png images to attach
for file in os.listdir(picFolder):
    if str(file).find(".jpg") > -1:
       pos = int(str(file).find("."))
       newfile = str(file)[0:pos]
       cursor.insertRow((newfile, file))
del cursor

arcpy.AddAttachments_management(input, inputField, matchTable, matchField, pathField, picFolder)

Tags: intest路径脚本错误managementtempfile
1条回答
网友
1楼 · 发布于 2024-10-01 00:29:15

从您的错误“'c:\temp\match1\jpg\n/”,我可以看到“\n”字符,\n是新行的符号(当您按回车键时),您应该从路径的末尾删除该字符!你试过这么做吗?可以使用.lstrip(“\n”)、replcae()或regx方法删除该字符

试着像这样逐行打开并读取输入文件:

read_lines = [line.rstrip('\n') for line in open(r"C:\temp\Match1\Match_Table.txt")]
print(read_lines)
print(read_lines[1])

相关问题 更多 >