在python中复制文件时的空白文件

时间:2015-07-31 01:32:15

标签: function python-3.x text-processing

我有一个函数将文件作为输入并打印某些统计信息,并将文件复制到用户提供的文件名中。这是我目前的代码:

UPDATE cust SET Balance = cl.Balance
FROM 
    cust 
    INNER JOIN [#custnumtbl] tmp ON cust.CustNum = tmp.CustNum
    LEFT OUTER JOIN CLedger cl ON 
        cl.CustNum = cust.CustNum 
        AND PDate = (SELECT MAX(PDate) FROM CLedger WHERE CustNum = cl.CustNum)

它正确打印文件的统计信息,但是它对文件的复制是空的。如果我删除def copy_file(option): infile_name = input("Please enter the name of the file to copy: ") infile = open(infile_name, 'r') outfile_name = input("Please enter the name of the new copy: ") outfile = open(outfile_name, 'w') slist = infile.readlines() if option == 'statistics': for line in infile: outfile.write(line) infile.close() outfile.close() result = [] blank_count = slist.count('\n') for item in slist: result.append(len(item)) print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format( len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count))) copy_file('statistics') 部分和统计信息部分,该函数似乎正确地复制了该文件。如何更正我的代码以便它们同时执行。这是一个小问题,但我似乎无法得到它。

1 个答案:

答案 0 :(得分:2)

文件为空的原因是

slist = infile.readlines()

正在读取文件的全部内容,所以当它到达

 for line in infile:

没有什么可以阅读的,它只是关闭新截断的(模式w)文件,留下一个空白文件。

我认为这里的答案是将您的for line in infile:更改为for line in slist:

def copy_file(option):
    infile_name= input("Please enter the name of the file to copy: ")
    infile = open(infile_name, 'r')
    outfile_name = input("Please enter the name of the new copy:  ")
    outfile = open(outfile_name, 'w')
    slist = infile.readlines()
    if option == 'statistics':
        for line in slist:
            outfile.write(line)
        infile.close()
        outfile.close()
        result = []
        blank_count = slist.count('\n')
        for item in slist:
            result.append(len(item))
        print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format(
            len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count)))


copy_file('statistics')

说了这么多,考虑是否值得使用自己的复制例程而不是shutil.copy - 总是更好地将任务委派给你的操作系统,因为它会更快,更安全(感谢NightShadeQueen提醒)!