目前正試圖在 python 中回圈一個帶有地址的檔案,但由于某種原因而不是回圈整個檔案 - 它在第一行停止。
我嘗試重置計數器并使其回傳第一個 if 陳述句,但它仍然只吐出第一個地址并繼續列印其他行。
如果您有任何建議,我將不勝感激!
我的代碼:
starter_file = 'addresses.csv'
output_file = 'new_address.csv'
new_address = ''
line_counter = 0
def save_file(filename, file_mode, content):
with open (filename, mode=file_mode, encoding='utf-8') as output_file:
output_file.write(content)
with open(starter_file, mode='r') as map_data:
for each_line in map_data.readlines():
if line_counter == 0:
header = 'street, city, state, zip, coordinates\n'
save_file(output_file, 'a ', header)
if line_counter == 1: # street
new_address = each_line[1:].strip() # remove initial ", strip \n from enconding
if line_counter == 2: # city, st, zip
city_state_zip = each_line.strip()
city_end = len(each_line) - 8
city = city_state_zip[:city_end]
state = city_state_zip[city_end:city_end 2]
zip_code = city_state_zip[-5:]
new_address = new_address ', ' city state ', ' zip_code
if line_counter == 3: # coordinates
new_address = new_address ', ' each_line.replace(',', ';')
save_file(output_file, 'a ', new_address)
if line_counter > 3:
line_counter == 1
print('#' str(line_counter) ' >> ', new_address)
line_counter = 1
輸出:
#0 >>
#1 >> 330 Utica Avenue
#2 >> 330 Utica Avenue, Brooklyn, NY , 11213
#3 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
#4 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
#5 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
#6 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
#7 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
#8 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
#9 >> 330 Utica Avenue, Brooklyn, NY , 11213, (40.66668313300005; -73.93135881299997)"
然后它繼續回圈。
uj5u.com熱心網友回復:
它可能是您代碼的以下部分嗎?
if line_counter > 3:
line_counter == 1
# ...
line_counter = 1
當 時line_counter > 3,它本質上是2在下一次迭代開始時設定的。
相反,您可以if完全洗掉該陳述句并將回圈的最后一行更改為line_counter = (line_counter 1) % 3. 如果您不熟悉模運算子( %),它會計算余數。在這種情況下,它會創建一個“環繞”效果,因此一旦line_counter達到 3,它就會“重置”為 0。
編輯:實際上,根據 Barmar 的評論,我現在意識到它line_counter應該只為零一次 - 所以上面的代碼不會很有幫助。我建議改用這個:
line_counter = (line_counter % 3) 1
這樣,一旦line_counter == 3,它環繞到 1 而不是 0。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/512671.html
