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

blank file while copying a file in python

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

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

它正确地打印了文件的统计信息,但是它制作的文件副本是空的。如果我删除 readline() 部分和统计部分,该函数似乎可以正确地复制文件。我怎样才能更正我的代码,以便它同时执行这两项操作。这是一个小问题,但我似乎无法理解。

文件为空的原因是

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 - 最好将任务委托给您的 OS,因为它会更快并且可能更安全(感谢提醒 NightShadeQueen)!