如何在Python中复制文件?
问题描述:
我需要复制用户指定的文件并复制它(给它一个用户指定的名称)。这是我的代码:如何在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的内容。
答
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)
答
如果你正在阅读outfile,你为什么用'w+'
打开它?这会截断该文件。使用'r'
来阅读。请参阅link
+0
当我将它更改为'w'时,它仍然不起作用。 – 2013-03-05 19:17:15
答
为什么不直接将输入文件内容写入输出文件?
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)
你失去了你的输出文件名,并没有复制操作发生。
使用'shutil.copy' – mgilson 2013-03-05 18:59:05
这看起来像一个重复的,检查了这一点:http://stackoverflow.com/questions/123198/how-do-i-copy-a- file-in-python – 2013-03-05 19:30:12
@MichaelW谢谢! – 2013-03-06 01:42:38