2016-06-20 15 views
2

我有一堆的文件路徑:一旦定義的ID號,並使用它的每一個文件路徑

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

您可以對此使用正則表達式 - 但爲什麼你想要?爲什麼不只是像「C:\\ file \\ path \\ here \\ place1 _」+ ID +「。shp」那樣追加字符串? – OneRaynyDay

回答

0
ID = "2001" 

place1 = "C:\\file\\path\\here\\place1_" + ID + ".shp" 

請注意圍繞ID值「2001」的引號,它使它成爲一個字符串,它允許您將其添加到其他字符串。否則,你最終會遇到一個TypeError,當你嘗試將整數添加到字符串時會出現。

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瞭解更多信息。

+0

謝謝你真正獲得正確的字符串格式版本。 – Chris

相關問題