Python 2.7 如何将其定向到文件

Python 2.7 如何将其定向到文件,python-2.7,Python 2.7,这不是指向文件p with open('/var/tmp/out3') as f: before = collections.deque(maxlen=1) for line in f: if 'disk@g5000cca025a1ee6c' in line: sys.stdout.writelines(before) p.write(before) 试试这个: import sys file

这不是指向文件p

with open('/var/tmp/out3') as f:
       before = collections.deque(maxlen=1)
       for line in f:
          if 'disk@g5000cca025a1ee6c' in line:
                sys.stdout.writelines(before)
          p.write(before)
试试这个:

import sys

filename = '/var/tmp/out3'
expression = 'disk@g5000cca025a1ee6c'

with open(filename, 'r') as f:
with open('p', 'w') as p_file:
    previous = next(f)
    for line in f:
        if expression in line:
            p_file.write(previous)
        previous = line
如果找到
表达式
,则应在当前目录中找到包含该表达式的文件
'p'

当我在Python2.7.10上试用时,它起了作用。我从这个答案中提取了密码


希望这有帮助。

您是否在代码中的某个地方声明了
'p'
?因为在此代码中没有定义
p
。您可能需要声明
'p'
文件,类似于
将open('/var/tmp/out3')声明为f:with open('p_file.txt','w')声明为p:
…等等,我声明p为文件。好的。你的代码对我有用。哪部分不适合你?您是否有任何错误?我想将deque的输出写入一个文件。请检查以下错误:代码工作正常,谢谢。但我需要将输出指向另一个文件我的错误,您是对的,我忘记将输出改为直接指向文件。我已经更新了答案。很高兴它对您有效,如果答案回答了您的问题,请勾选“接受”。谢谢@Ahmedi我刚到这个我应该打勾的网站。请通知。没关系,不用担心:)答案左边应该有一个“打勾”按钮,你可以按下,勾选“绿色”,看看这个:谢谢