我有一堆文件路径:
shapefile = "C:\\file\\path \\here\\this\\one\\is\\different\\2001_6W.shp"
place1 = "C:\\file\\path\\here\\place1_2001.shp"
place2 = "C:\\file\\path\\here\\place2_2001.shp"
place3 = "C:\\file\\path\\here\\place3_2001.shp"
如果我可以定义数字ID(2001)然后将它用在文件名中,我希望如此:
ID = 2001
shapefile = "C:\\file\\path \\here\\this\\one\\is\\different\\ID_6W.shp"
place1 = "C:\\file\\path\\here\\place1_ID.shp"
place2 = "C:\\file\\path\\here\\place2_ID.shp"
place3 = "C:\\file\\path\\here\\place3_ID.shp
有办法做到这一点吗?我不确定我是否解释了我想要的东西。
答案 0 :(得分:3)
您应该使用字符串格式,如下所示:
ID = 2001
# Positionally replace {}
place1 = "c:\\file\\path\\here\\place1_{}.shp".format(ID)
# It also works with keywords!
place2 = "c:\\file\\path\\here\\place2_{id}.shp".format(id=ID)
如果你想有时使用整数或其他时候使用字符串,这会让它变得类型不明确。它也可以根据需要处理多个部分,因此您可以循环播放;
ID = 2001
places = {}
for place_number in range(10):
places[place_number] = "c:\\file\\path\\here\\place{}_{}.shp".format(place_number, ID)
# OR #
places[place_number] = "c:\\file\\path\\here\\place{place}_{id}.shp".format(place=place_number, id=ID)
编辑:字符串格式还有更多内容,请参阅python documentation了解更多信息。
答案 1 :(得分:0)
ID = "2001"
place1 = "C:\\file\\path\\here\\place1_" + ID + ".shp"
注意ID值“2001”周围的引号,这使得它成为一个字符串,允许您将其添加到其他字符串。否则,当您尝试将整数添加到字符串时,最终会出现TypeError。