0

Hello I'm new to python and I'd like to know how to process a .txt file line by line to copy files specifid as wild cards

basically the .txt file looks like this.

bin/
bin/*.txt
bin/*.exe
obj/*.obj
document
binaries

so now with that information I'd like to be able to read my .txt file match the directory copy all the files that start with * for that directory, also I'd like to be able to copy the folders listed in the .txt file. What's the best practical way of doing this? your help is appreciated, thanks.

  • Step 1. Search. This is already well covered by [Python search file using wildcard](http://stackoverflow.com/questions/3348753/python-search-file-using-wildcard) – S.Lott Apr 08 '11 at 01:22

2 Answers2

2

Here's something to start with...

import glob # For specifying pathnames with wildcards
import shutil # For doing common "shell-like" operations.
import os # For dealing with pathnames

# Grab all the pathnames of all the files matching those specified in `text_file.txt`
matching_pathnames = []
for line in open('text_file.txt','r'):
    matching_pathnames += glob.glob(line)

# Copy all the matched files to the same filename + '.new' at the end
for pathname in matching_pathnames:
    shutil.copyfile(pathname, '%s.new' % (pathname,))
Chris W.
  • 37,583
  • 36
  • 99
  • 136
  • I tried your suggestiong I can't figure out why but for the first for loop I'm getting a no such file or directory error message. In your for loop you're not specifiying the source folder. I can't figure out how to glob.glob(*.txt) using my source.txt file. As a test when I do this in one line glob.glob(*.exe) it works great I can't figure out how to put this togeher in a script where the *.exe inside the () is read from my fileinfo.txt – user697023 Apr 08 '11 at 01:11
  • @user697023 so the first for loop is supposed to loop through the lines of the text file specified in `open()`. If you're getting a no such file error when trying to open that file that just means that you're not using the proper path to that file. You should provide either the 'absolute' (full) path to the file or the path relative to the directory where you start the python interpreter. – Chris W. Apr 08 '11 at 16:39
1

You might want to look at the glob and re modules

http://docs.python.org/library/glob.html

Alan
  • 376
  • 1
  • 7