[英]Python - File processing ( Write Method )
I am having trouble while writing file using python 使用python写入文件时遇到麻烦
from validate_email import validate_email
result=open('output1.tsv','wb')
f=open('input.csv','r')
y=[]
result.write('Email_address\tEmail_validation\n')
for i in f:
y.append(i.replace('\n',''))
for j in y:
try:
val=validate_email('%s'%j, verify=True)
except:
val = "Check Again"
result.write('%s\t%s\n'%(j,val))
print j,val
Here the variable x has some operation , It may take some time to process it. 在这里,变量x有一些运算,可能需要一些时间来处理它。
variable y has more than a count of 500 ( input file contains 700 rows ). 变量y的计数超过500(输入文件包含700行)。
But after run this program around 120 only written in the output file. 但是运行此程序后大约只有120个写入输出文件中。
A more idiomatic python is 一个更惯用的python是
emails = [l.strip() for l in open('input.csv','r').readlines()]
valid = [str(validate_email(addr, validate=1)) for addr in emails]
validated = ['\t'.join(addr_val) for addr_val in zip(emails, valid)]
with of as open('output.tsv'):
of.write('Email_address\tEmail_validation\n')
of.write('\n'.join(validated)) # if needed ; of.write('\n')
To take into account the possibility of a TimeoutError
exception, that is likely raised by the smtp
module, you can write an helper function 考虑到smtp
模块可能引发的TimeoutError
异常,您可以编写一个辅助函数
def validate_no_timeout(address):
try:
response = str(validate_email(address, validate=1))
except TimeoutError:
response = "Time Out"
return response
and rewrite the second line in my original post to read 并在我的原始帖子中重写第二行以阅读
valid = [validate_no_timeout(addr) for addr in emails]
NB: in the OP I see a generic reference to a Time Out error . 注意:在OP中,我看到了有关超时错误的通用参考。 In my code I catched the TimeoutError
exception, in lack of exact info from the OP. 在我的代码中,由于缺少OP的确切信息,我捕获了TimeoutError
异常。
You have use a string when writing to file try changing it to: 您在写入文件时使用了一个字符串,尝试将其更改为:
t.write('%d\t%d\n'%(j,x))
If this doesn't fix it, try expanding the code in your question so we can help more. 如果仍不能解决问题,请尝试扩展问题中的代码,以便我们提供更多帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.