Bhavika Bhavika - 2 months ago 19
Python Question

Reading a text file and moving files from it to a directory

I have a directory of images. Some of these images must be stored in a text file like 'pic1.jpg'

I need to extract this filename, pick up the matching file from the current working directory and move it to a separate folder (under the cwd).

This is the code I have so far, but I cant get the shutil operations to work. What am I doing wrong?

Current directory C:\BE

Have to move a file(s) 1,jpg, 2,jpg etc from a textfile called "filelist.txt" to 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()

Answer

This is what finally worked -

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()