复制和重命名文件

时间:2014-02-03 06:00:22

标签: python

我正在尝试根据csv文件的内容复制和重命名文件的多个副本。

当我打印要运行的命令时,下面的代码似乎产生了正确的结果,但是,当实际执行命令时,注意被复制,而我最终会得到许多打开和空白的cmd窗口。这是Windows权限问题吗?

import os
import csv 
file_location1 = "blank.mpp" 
csv_file_location ="all_projects_2014.csv" 

with open(csv_file_location,'r') as f: 
    contents = csv.reader(f) 
    for row in contents: 
        second_file = str(row) 
        second_file = second_file.translate(None, '[\']')+'.mpp' 
        command = "cp %s %s" % (file_location1, second_file) 
        os.system(command) 
        #print command

2 个答案:

答案 0 :(得分:0)

cp不是Windows的有效命令。您必须在Windows中使用copy命令。

由于不同的平台有不同的命令所以我建议你使用shutil。复制(...)

如果您只想在Windows上运行代码,请尝试以下操作:

import os
import csv 
file_location1 = "blank.mpp" 
csv_file_location ="all_projects_2014.csv" 

with open(csv_file_location,'r') as f: 
    contents = csv.reader(f) 
    for row in contents: 
        second_file = str(row) 
        second_file = second_file.translate(None, '[\']')+'.mpp' 
        command = "copy \"%s\" \"%s\"" % (file_location1, second_file) 
        os.system(command)

答案 1 :(得分:0)

为什么不使用python shutil

给出的复制方法
from shutil import copy
shutil.copy(file_location1, second_file)


>>> help(shutil.copy)
Help on function copy in module shutil:
copy(src, dst)
    Copy data and mode bits ("cp src dst").
    The destination may be a directory.

>>> help(shutil.copy2)
Help on function copy2 in module shutil:
copy2(src, dst)
    Copy data and all stat info ("cp -p src dst").
    The destination may be a directory.