从CSV读取文件名,然后将文件复制到其他目录 [英] Read filenames from CSV and then copy the files to different directory

查看:171
本文介绍了从CSV读取文件名,然后将文件复制到其他目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够编写一个批处理文件来查找文件,并将文件路径放入CSV文件中.我一直无法弄清楚如何从CSV读取文件位置,然后使用python将文件移动到具有相同文件夹结构的其他存储设备.这就是我想做的.

I have been able to write a batch file to find files and put the file paths into a CSV. I haven't been able to figure out how to read the file locations from the CSV and then move the files to a different storage device with the same folder structure using python. This is what I'd like to do.

我希望我能向您展示一些代码,但是没有一个起作用.

I wish I had some code to show you but none of it has worked.

推荐答案

在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!'

这篇关于从CSV读取文件名,然后将文件复制到其他目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆