2013-03-05 54 views
1

我需要複製用戶指定的文件並複製它(給它一個用戶指定的名稱)。這是我的代碼:如何在Python中複製文件?

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的內容。

+11

使用'shutil.copy' – mgilson 2013-03-05 18:59:05

+0

這看起來像一個重複的,檢查了這一點:http://stackoverflow.com/questions/123198/how-do-i-copy-a- file-in-python – 2013-03-05 19:30:12

+0

@MichaelW謝謝! – 2013-03-06 01:42:38

回答

0

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

如果你正在閱讀outfile,你爲什麼用'w+'打開它?這會截斷該文件。使用'r'來閱讀。請參閱link

+0

當我將它更改爲'w'時,它仍然不起作用。 – 2013-03-05 19:17:15

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

什麼副本所做的是,它的淺拷貝蟒蛇的對象,無關與複製文件。

什麼這條線實際上做的是,它複製輸入文件內容對輸出文件的名稱:

userfile2 = copy.copy(file_contents) 

你失去了你的輸出文件名,並沒有複製操作發生。