2015-03-25 166 views
0

我正在尝试创建一个脚本,它以文件作为输入,查找所有电子邮件地址并将它们写入指定文件。使用Python打印输出到文件

基于其他类似的问题,我已经结束了与此:

import re 

    Input = open("inputdata.txt", "r") 
    regex = re.compile("\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}\b") 
    Logfile = "Result.txt" 


     for line in Input: 
      query = regex.findall(line) 
      for line in query: 
       print >>Logfile, query 

我到底做错了什么?这不输出。 我猜测主要问题是“对于查询中的行:”,我试图改变没有任何运气。

干杯!

编辑:我改变了脚本,如下所示,用“打印(查询)”代替。 我仍然没有得到任何输出。 当前的脚本是:

import re 

Input = open("Inputdata.txt", "r") 
regex = re.compile("\b[A-Z0-9._%+-][email protected][A-Z0-9.-]+\.[A-Z]{2,4}\b") 
# logfile = "Result.txt" 

for line in Input: 
    query = regex.findall(line) 
    for line in query: 
     with open("Result.txt", "a") as logfile: 
      logfile.write(line) 

它输出什么,并告诉我: “NameError:名字 ”日志文件“ 没有定义”。 是什么原因造成的,这是没有输出的原因吗?

+0

关于您的编辑:我没有收到该代码的名称错误;你确定你正在使用这个确切的代码吗?请注意,我将变量从'Logfile'更改为'logfile'(即小写),以符合编码约定。此外,您不必在每次迭代中重新打开该文件。将'with ...'行移到循环的顶部。 – 2015-03-25 12:08:25

回答

1

您的Logfile变量只是名称的文件,而不是实际的file对象。此外,您应该使用with在完成后自动关闭文件。试试这个:

with open("Result.txt", "a") as logfile: 
    print >>logfile, "hello world" 
    print >>logfile, "another line" 

但需要注意的是Python 3.x中,语法是不同的,因为print不再是一个声明,但a function

with open("Result.txt", "a") as logfile: 
    print("hello world", file=logfile) 
    print("another line", file=logfile) 

因此,而不是重定向print,最好的选择可能是直接将write添加到文件中:

with open("Result.txt", "a") as logfile: 
    logfile.write("hello world\n") 
    logfile.write("another line\n") 
+0

非常感谢。 工作脚本如下所示,现在输出正确: import re Input = open(“Input.txt”,“r”) regex = re.compile(“\ b [A-Z0-9._ %+ - ] + @ [A-Z0-9 .-] + \。(AZ){2,4} \ b“) #logfile = open(”Result.txt“,”a“) 以开放(”Result.txt“,”a“)作为日志文件: 输入: query = regex.findall(line) for input in:输入: logfile.write(query) – Krisem 2015-03-25 12:33:37

0

我不认为,与print你可以写入文件,而不必将输出重定向到一个文件。我猜你已经使用了print,你只需要输出重定向。

假设您的python脚本位于文件test.py中。 更换行:

print >>Logfile, query 

只:

print query 

而从终端/ CMD,运行脚本是这样的:

python test.py >> Result.txt 

这被称为输出重定向。