[英]Read filenames from CSV and then copy the files to different directory
I have been able to write a batch file to find files and put the file paths into a CSV. 我已经能够编写一个批处理文件来查找文件,并将文件路径放入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.
我一直无法弄清楚如何从CSV读取文件位置,然后使用python将文件移动到具有相同文件夹结构的其他存储设备。 This is what I'd like to do.
这就是我想做的。
I wish I had some code to show you but none of it has worked. 我希望我有一些代码可以显示给您,但是没有一个起作用。
Here's a quick and dirty solution. 这是一个快速而肮脏的解决方案。 (I haven't tested it yet, YMMV!)
(我尚未测试,YMMV!)
import csv
import os
import shutil
import sys
def main(argv):
# TODO: this should do some error checking or maybe use optparse
csv_file, existing_path_prefix, new_path_prefix = argv[1:]
with open(csv_file, 'rb') as f:
reader = csv.reader(f)
for row in reader:
# Assuming the column in the CSV file we want is the first one
filename = row[0]
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...' % filename, new_filename),
shutil.copy(filename, new_filename)
print 'done.'
print 'All done!'
if __name__ == '__main__':
main(sys.argv)
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. 在Daniel的帖子中,由于他确实警告过他尚未测试:),所以我认为您需要进行一些小改动。 Basically, I think the issue in the suggested code is that
filename
is assumed to be the full path. 基本上,我认为建议代码中的问题是假定
filename
是完整路径。 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. 但是,当您进入
os.path.join
命令以获取new_filename
时,这会产生问题,因为您要向完整路径和名称添加新路径。
I would suggest including a filepath
and filename
in your csv to make the code run. 我建议在csv中包含
filename
filepath
和filename
以使代码运行。 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): 尽管我没有作为函数运行(并且我为Python 3.4语法使用了
print()
语句print()
,但这些更改似乎在我测试时起作用了:
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!'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.