我有一个图像目录。其中一些图像必须存储在文本文件中,例如' pic1.jpg'
我需要提取此文件名,从当前工作目录中选取匹配文件并将其移至单独的文件夹(在cwd下)。
这是我到目前为止的代码,但我不能让shutil操作工作。我究竟做错了什么?
当前目录C:\ BE
必须从名为" filelist.txt"的文本文件中移动文件1,jpg,2,jpg等。到C:\ BE \ 2014-03-25_02-49-11
import os, datetime
import shutil
src = os.getcwd()
global mydir
def filecreation(content, filename):
mydir = os.path.join(os.getcwd(), datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
try:
os.makedirs(mydir)
except OSError, e:
if e.errno != 17:
raise # This was not a "directory exist" error..
with open(os.path.join(mydir, filename), 'w') as d:
d.writelines(content)
#shutil.copyfile(src,mydir)
def main():
filelist = "filelist.txt"
with open(filelist) as f:
content = f.read().splitlines()
#content = shutil.copyfile(src, mydir)
print content
print "Here we are"
#list=['1.jpg','2.jpg']
filecreation(content,"filelist.txt")
print "lets try another method"
with open('filelist.txt','w+') as list_f:
for filename in list_f:
with open(filename) as f:
content = f.read()
#content = shutil.move(src,mydir)
#content = shutil.copyfile(src,mydir)
#for line in f
print "method 2 is working so far"
if __name__ == '__main__':
main()
答案 0 :(得分:1)
这是最终奏效的 -
from shutil import copy
f = open(r'C:\Users\B\Desktop\BE Project\K\filelist.txt', 'r')
for i in f.readlines():
print i
copy(i.strip(),r"E:\Images")
f.close()
答案 1 :(得分:0)
您已走上正轨。我可以看到你已经尝试过模块shutil
您可以尝试此功能shutil.move