Bhavika Bhavika - 1 year ago 122
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(),'%Y-%m-%d_%H-%M-%S'))

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:


def main():

filelist = "filelist.txt"
with open(filelist) as f:
content =
#content = shutil.copyfile(src, mydir)
print content
print "Here we are"

print "lets try another method"
with open('filelist.txt','w+') as list_f:
for filename in list_f:
with open(filename) as f:
content =
#content = shutil.move(src,mydir)
#content = shutil.copyfile(src,mydir)
#for line in f
print "method 2 is working so far"

if __name__ == '__main__':


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download