2014-09-03 131 views
0

有沒有原因,這是代碼沒有寫入文件。除了寫作部分之外,其他一切都適用於此我知道我需要關閉該文件,但我不確定如何?由於某種原因Python沒有寫入文件

import os 
import sys 
import csv 
import pysftp as sftp 

with open('c:/Python27/log_07032014_1512.txt','r') as inf,  
open('C:/Python27/Errors.txt','w')as outf: 
reader = csv.reader(inf) 
writer = csv.writer(outf) 
for line in inf: 
    if 'Error' in line: 
     print line 

def sftpExample(): 
try: 
    s = sftp.Connection('***.***.***.***', username = '******', password = '****') 
    remotepath ='/home/*****/BOA.txt' 
    localpath = 'C:/Python27/Errors.txt' 
    s.put(localpath,remotepath) 

    s.close() 
except Exception, e: 
    print str(e) 

sftpExample() 
+1

你能解決你的代碼縮進? – 2014-09-03 22:15:05

回答

3

除非我失去了一些東西,我沒有看到你寫入文件:

for line in inf: 
    if 'Error' in line: 
     writer.writerow(line) 

如果你想檢查是否有特定的「列」包含錯誤,因爲喬恩·克萊門茨暗示下面,你應該遍歷CSV閱讀輸出不超過原始文件:

for line in reader: 
     if 'Error' in line: 
      writer.writerow(line) 
+0

儘管我同意你沒有任何實際上試圖寫入輸出流的事情,但可能有爭議的是,也許這是一個真正的測試,使用'csv.reader'來檢查處理過的行中的任何*列*是否包含「Error」而不是原始行本身的一個簡單的子串檢查。 – 2014-09-03 22:20:00

+0

這很有道理。我會相應地調整我的評論。 – ventsyv 2014-09-03 22:27:50

0

好吧,我不知道我理解正確的,但:

  • 您似乎沒有正確縮進。 infoutf打開的文件只能在with方面:

    with open('c:/Python27/log_07032014_1512.txt','r') as inf, open('C:/Python27/Errors.txt','w')as outf: 
        print 'the files are open in this context' 
    print 'the files are now closed' 
    

您不必關閉文件。

  • 您似乎沒有寫入輸出文件。

我無法理解正在使用的文件格式,因此,如果他們是文本文件,你應該:

with open('c:/Python27/log_07032014_1512.txt','r') as inf, open('C:/Python27/Errors.txt','w')as outf: 
     for line in inf: 
      if 'Error' in line: 
       outf.write(line) 

如果他們的CSV:

with open('c:/Python27/log_07032014_1512.txt','r') as inf, open('C:/Python27/Errors.txt','w')as outf: 
     reader = csv.reader(inf) 
     writer = csv.writer(outf) 
     for line in reader: 
      if 'Error' in line: 
       writer.writerow(line) 
+0

我實際上已經打印出正確的文件,我需要它來寫入新文件。這實際上是一個txt文件 – zooted 2014-09-04 00:26:36

+0

因此,我的答案中的第二塊代碼是你需要的。您可以刪除閱讀器和作者,因爲他們沒有被您的代碼使用。唯一缺少的是你正在打印行('print line')而不是寫入文件('outf.write(line)') – rhlobo 2014-09-04 03:22:05

相關問題