【发布时间】:2013-02-05 19:20:25
【问题描述】:
我正在使用此 python 代码从给定文件 (source_file.txt) 中提取电子邮件地址,并将这些电子邮件地址写入单独的文件中。 (我使用的是 python 3.3)
import urllib.request
import re
import fileinput, glob, string, sys, os
from os.path import join
import os
filePath = "source_file.txt"
if not filePath:
print("Sorry! Source File could not be located!")
else:
page = open(filePath, "r")
pageContent = page.read()
page.close()
style_normal = re.compile("[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
style_text_one = re.compile('[-a-zA-Z0-9._]+\s+at\s+[-a-zA-Z0-9_]+\s+dot\s+[a-zA-Z0-9_.]+')
style_text_two = re.compile('[-a-zA-Z0-9._]+\(at\)[-a-zA-Z0-9_]+\(dot\)[a-zA-Z0-9_.]+')
style_normal_list = style_normal.findall(str(pageContent))
style_text_one_list = style_text_one.findall(str(pageContent))
style_text_two_list = style_text_two.findall(str(pageContent))
f = open('emails_file.txt', 'a')
f.write('testing')
for item in style_normal_list:
print("%s" %item)
f.write("%s" %item)
for item in style_text_one_list:
text_one = item.replace(' at ','@')
text_two = text_one.replace(' dot ','.')
print(text_two)
f.write(text_two)
for item in style_text_two_list:
text_one = item.replace('(at)','@')
text_two = text_one.replace('(dot)','.')
f.write(text_two)
问题是当我运行这个文件时,文件被创建了,但文件中没有写入任何内容。甚至没有文字“测试”。文件已创建但为空白。
我已经使用打印语句来检查代码的其他部分是否正常工作。 根据python doc,语法是正确的。 谁能指出我在这段代码中犯的任何错误?
【问题讨论】:
-
这可能无关紧要,但请尝试在脚本末尾添加
f.close()。 -
或者,最好将
f = open('emails_file.txt', 'a')替换为with open('emails_file.txt', 'a') as f:并缩进脚本的其余部分。 -
我试过@WarrenWeckesser 的方法 f.close() 确实有效。无法想象我因为这种简单的事情而挣扎了这么久:) 谢谢!也得试试 abarnert 谢谢!
标签: python regex python-3.x file-io python-requests