简体   繁体   中英

How to Write to a file and then read the file in Python

I have written the following code:

supported = open("Mails/mymails.txt",'w')
with open("emails.txt","r") as handle:
    for line in handle:
        if line.strip():
            list = line.split(":")
            email = list[0]
            domain = email.split("@")
            if domain[1] in blacklist:
                blacklisted = blacklisted+1
            if domain[1] in dictionary and domain[1] not in blacklist:
                valid=valid+1
                supported.write(domain[1])
            
    print(valid,blacklisted)
with open("Mails/mymails.txt",'r') as handle1:

    for line1 in handle1:
        print(line1)

I used append mode and it worked fine, but when i use multiple files, i have to manually delete supported.txt file to make sure the new file lines are not appended to old file lines Any help is appreciated

I closed the file and it worked fine

like: supported.close() at the end of first with statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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