循环运行不正常

Loop Not Functioning well

伙计们,我的代码有点问题。该代码应该检查数字列表并将它们分组在基于文本文件提供程序中,但没有按预期工作。它只为每个提供者而不是多个提供者在文件中保存一个数字。这是我的代码,如果有人可以帮助我 grateful.Sorry 如果我的代码太传统

def main():
     dead = open('invalid_no.txt', 'a+')
     print('-------------------------------------------------------')
     print('-------------------------------------------------------')
     list = input('Your Phone Numbers List : ')

     base_url = "http://apilayer.net/api/validate"

     params = {
         'access_key': '3246123d1d67e385b1d9fa11d0e84959',
         'number': '',
               }

     numero = open(list, 'r')


     for num in numero:
         num = num.strip()
         if num:
             lines = num.split(':')
        
             params['number'] = lines[0]
        
             response = requests.get(base_url, params=params)
             
             print('status:', response.status_code)
             print('-------------------------------------')

             try:                 
                 resp = response.json()
                 print('number:', resp['valid'])
                 print('number:', resp['international_format'])
                 print('country:', resp['country_name'])
                 print('location:',resp['carrier'])
                 print('-------------------------------------')    
                 mok = open(resp['carrier'],'w+')      
                 if resp['carrier'] == mok.name:
                    mok.write(num +'\n')
             except FileNotFoundError:
                 if resp['carrier'] == '':
                    print('skipping')
                 else:
                    mok = open(resp['carrier'],'w+')
                    if resp['carrier'] == mok.name:
                     mok.write(num)
                    else:
                     print('No')
if __name__ == '__main__': main()

"w" 模式打开文件将删除现有文件并从一个空的新文件开始。这就是为什么你只得到一个数字。每次写入文件时,都会覆盖之前的内容。没有模式 "w+"。我相信这应该会导致 ValueError: invalid mode: 'w+',但实际上它似乎与 "w" 一样。 "r+" 存在的事实并不意味着您可以推断出还有一个未记录的 "w+".

来自 open() 的文档:

The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

所以,没有 "w+"

我认为您需要模式 "a" 进行追加。但是如果你这样做,你的代码第一次尝试写入文件时,它不会在那里追加,所以你会得到找不到文件的错误,你遇到了问题。

在写入文件之前,请检查它是否存在。如果没有,打开它进行写入,否则打开它进行追加。

if os.path.exists(resp['carrier']):
    mok = open(resp['carrier'],'a')
else: 
    mok = open(resp['carrier'],'w')

或者,如果您喜欢 one-liners,

mok = open(resp['carrier'],'a' if os.path.exists(resp['carrier']) else 'w')

此外,您的代码在文件写入完成后永远不会调用 close()。这应该。忘记它可能会导致数据丢失或其他令人困惑的行为。

不要忘记它的最好方法是使用上下文管理器:

with open(resp['carrier'],'a' if os.path.exists(resp['carrier']) else 'w') as mok:
    # writes within the with-block here
# rest of program here
# after the with-block ends, the context manager closes the file for you.