1

我需要复制用户指定的文件并复制它(给它一个用户指定的名称)。这是我的代码:

import copy

def main():

    userfile = raw_input('Please enter the name of the input file.')
    userfile2 = raw_input('Please enter the name of the output file.')

    infile = open(userfile,'r')

    file_contents = infile.read()

    infile.close()

    print(file_contents)


    userfile2 = copy.copy(file_contents)

    outfile = open(userfile2,'w+')

    file_contents2 = outfile.read()

    print(file_contents2)

main()

这里发生了一些奇怪的事情,因为它不打印第二个文件 outfile 的内容。

4

3 回答 3

3

如果您正在阅读 outfile,为什么要使用'w+'? 这会截断文件。

用于'r'阅读。见链接

于 2013-03-05T19:12:14.270 回答
1

Python 的 shutil 是一种更便携的文件复制方法。试试下面的示例:

import os
import sys
import shutil

source = raw_input("Enter source file path: ")
dest = raw_input("Enter destination path: ")

if not os.path.isfile(source):
    print "Source file %s does not exist." % source
    sys.exit(3)

try:
    shutil.copy(source, dest)
except IOError, e:
    print "Could not copy file %s to destination %s" % (source, dest)
    print e
    sys.exit(3)
于 2013-03-05T21:06:11.473 回答
0

为什么不直接将输入文件内容写入输出文件呢?

userfile1 = raw_input('input file:')
userfile2 = raw_input('output file:')

infile = open(userfile1,'r')
file_contents = infile.read()    
infile.close()

outfile = open(userfile2,'w')
outfile.write(file_contents)
outfile.close()

复制的作用是对python中的对象进行浅复制,与复制文件无关。

该行实际上所做的是将输入文件内容复制到输出文件的名称上:

userfile2 = copy.copy(file_contents)

您丢失了输出文件名,并且不会发生复制操作。

于 2013-03-05T19:23:58.710 回答