![](/img/trans.png)
[英]Read filenames from CSV and then copy the files to different directory -part 2
[英]Read filenames from CSV and then copy the files to different directory
我已经能够编写一个批处理文件来查找文件,并将文件路径放入CSV文件中。 我一直无法弄清楚如何从CSV读取文件位置,然后使用python将文件移动到具有相同文件夹结构的其他存储设备。 这就是我想做的。
我希望我有一些代码可以显示给您,但是没有一个起作用。
这是一个快速而肮脏的解决方案。 (我尚未测试,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)
在Daniel的帖子中,由于他确实警告过他尚未测试:),所以我认为您需要进行一些小改动。 基本上,我认为建议代码中的问题是假定filename
是完整路径。 但是,当您进入os.path.join
命令以获取new_filename
时,这会产生问题,因为您要向完整路径和名称添加新路径。
我建议在csv中包含filename
filepath
和filename
以使代码运行。 尽管我没有作为函数运行(并且我为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.