繁体   English   中英

Python file.write(email + '\n') NameError: name 'email' is not defined

[英]Python file.write(email + '\n') NameError: name 'email' is not defined

我从我的代码中得到这个错误我不明白为什么它不工作

with open("emails.txt",'r') as file:
    for line in file:
        grade_data = line.strip().split(':')
        email = grade_data[0]
        password = grade_data[1]

with open("emails_sorted.txt",'a') as file:
    print(Fore.YELLOW + "Sorting email...")
    file.write(email + '\n')

with open("passwords.txt",'a') as file:
    print(Fore.YELLOW + "Sorting password...")
    passwordspecial = password + '!'
    file.write(passwordspecial + '\n')

print(Fore.GREEN + "Done!")

在显示的代码中, for line in file ,如果 file 为空,则不会运行循环,因此不会定义 email。 如果文件为空,请尝试停止进程,或为 email 设置默认值

遍历其他文本文件的内容,您将打开emails_sorted.txt 您可以通过保存从emails.txt读取的数据并在打开emails_sorted.txtpasswords.txt时再次遍历它来解决此问题:

emails = []
passwords = []

with open("emails.txt", "r", encoding="utf-8") as file:
    for line in file.readlines():
        grade_data = line.strip().split(":")
        emails.append(grade_data[0])
        passwords.append(grade_data[1])

with open("emails_sorted.txt", "a", encoding="utf-8") as file:
    print(Fore.YELLOW + "Sorting email...")
    for email in emails:
        file.write(email + "\n")

with open("passwords.txt", "a", encoding="utf-8") as file:
    print(Fore.YELLOW + "Sorting password...")
    for password in passwords:
        passwordspecial = password + "!"
        file.write(passwordspecial + "\n")

print(Fore.GREEN + "Done!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM