csv 代码未循环通过文件的其余部分或重置计数器

zu0ti5jz  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(150)

当前试图循环遍历一个带有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)"

然后继续循环。

7ivaypg9

7ivaypg91#

可能是代码的以下部分吗?

if line_counter > 3:
    line_counter == 1

# ...

line_counter += 1

line_counter > 3时,它在下一次迭代开始时基本上被设置为2
相反,你可以完全删除if语句,并将循环的最后一行改为line_counter = (line_counter + 1) % 3。如果你不熟悉modulo operator%),它会计算余数。在这种情况下,它会产生一个“环绕”效果,这样一旦line_counter达到3,它就会“重置”为0。
编辑:实际上,根据Barmar的评论,我现在意识到line_counter只应该为零一次--所以上面的代码没有多大帮助。我建议使用下面的代码:

line_counter = (line_counter % 3) + 1

这样一来,一旦line_counter == 3,它就会绕回1而不是0。

相关问题