不支持的操作:不可写的python

Len*_*rd 23 python python-3.x

电邮验证

#Email validator
import re

f= open ('ValidEmails.txt', 'w')

def is_email():
    email=input("Enter your email")
    pattern = '[\.\w]{1,}[@]\w+[.]\w+'
    file = open('ValidEmails.txt','r')
    if re.match(pattern, email):
        file.write(email)

        file.close
        print("Valid Email")
    else:
        print("Invalid Email")

#The Menu        
print("The Email validator progam \n")
print("What do you want to do\n")
print("Validate the Email")
print("Quit")

while True:
        answer=(input("Press V, or Q : "))
        if answer in("V" ,"v"):
            is_email()
        elif answer in("Q" ,"q"):
            break
        else:
            print("Invalid response")
Run Code Online (Sandbox Code Playgroud)

我想知道为什么我的数据不会写入磁盘.Python说我的操作不受支持.

is_email
    file.write(email)
io.UnsupportedOperation: not writable
Run Code Online (Sandbox Code Playgroud)

我应该将电子邮件转换为这样的字符串或

file.write(str(email))
Run Code Online (Sandbox Code Playgroud)

是别的什么的

我可能错过了很简单的事情.

tri*_*ook 57

您将变量"file"作为只读打开然后尝试写入它.使用'w'标志.

file = open('ValidEmails.txt','w')
...
file.write(email)
Run Code Online (Sandbox Code Playgroud)