且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从CSV读取文件名,然后将文件复制到其他目录

更新时间:2021-09-18 08:50:07

在Daniel的帖子中,由于他确实警告过他尚未测试:),我认为您需要做一些小改动.基本上,我认为建议代码中的问题是filename被假定为完整路径.但是,当您进入new_filenameos.path.join命令时,就会产生一个问题,因为要向新路径和名称添加新路径.

Adding to Daniel's post, since he did warn he hadn't tested it :), I think you'll need to make a couple small changes. Basically, I think the issue in the suggested code is that filename is assumed to be the full path. But then that creates a problem when you get to the os.path.join command for new_filename because you're adding a new path to a full path and name.

我建议在您的csv中包含一个filepathfilename以使代码运行.尽管我没有作为函数运行(并且我为Python 3.4语法使用了print()语句),但所做的更改似乎在我测试时起作用了:

I would suggest including a filepath and filename in your csv to make the code run. The changes appear to work when I testd it, although I didn't run as a function (and I used print() statements for Python 3.4 syntax):

with open(csv_file, 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
      # Assuming the columns in the CSV file we want are the first two  // Changed
      filename = row[0]
      filepath = row[1]   #Changed

     '''Changed: I skipped over this next part, didn't need it, but should be
     easy enough to figure out
     if filename.startswith(existing_path_prefix):
       filename = filename[len(existing_path_prefix):]
     '''

     new_filename = os.path.join(new_path_prefix, filename)

     print ('Copying %s to %s...' % filepath, new_filename)  #Changed
     shutil.copy(filepath, new_filename)   #Changed
     print 'done.'
print 'All done!'