2013-03-05 4 views
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의 내용이 인쇄되지 않으므로 이상하게 보입니다.

+11

사용'이 중복처럼 보이는 – mgilson

+0

을 shutil.copy'를,이 체크 아웃 : http://stackoverflow.com/questions/123198/how-do-i-copy-a- 파일 - 인 - 파이썬 –

+0

@MichaelW 고마워요! –

답변

0

파이썬의 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'로 변경하면 여전히 작동하지 않습니다. –

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) 

당신은 당신의 출력 파일 이름을 잃고 더 복사 작업이 발생하지 :

은 무엇이 행이 실제로하는 일은 출력 파일의 이름을 통해 그것을 복사 입력 파일의 내용이 있다는 것입니다.

관련 문제