Python由于某种原因没有写入文件

时间:2014-09-03 22:12:49

标签: python file-io

这是代码没有写入文件的原因吗?除了我知道我需要关闭文件的写作部分之外,其他所有工作都有用,但我不确定如何?

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()

2 个答案:

答案 0 :(得分:3)

除非我遗漏了某些内容,否则我没有看到你写信给该文件:

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

如果你想检查是否有任何特定的"列"包含错误,正如Jon Clements在下面建议的那样,你应该在原始文件上循环csv阅读器输出:

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

答案 1 :(得分: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)

如果他们是csvs:

    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)