Renaming files from txt within file

May 27, 2009 at 03:22:51
Specs: Windows XP
Please help!
I want to rename hundreds of files from my local directory by getting a string of text from the file.
For example: Filename: tsa012835182.txt
I want to rename it to include the text from within the file. The file contains several lines of text
15-05-09 003094 0610
15-05-09 003094 0715
15-05-09 003094 1715
15-05-09 003094 1807
I want to get 15-05-09 the first line in column 1, and then rename it as the name of the file.
The final filename should look like: TSA01-14-05-09.txt
Then proceed with the next file.
The 15-05-09 text is different in each file but in same location (column 1).

The final filename for this one should look like: tsa0115-05-09.txt


See More: Renaming files from txt within file

Report •


#1
May 27, 2009 at 04:38:15
if you have Python on windows
import glob,os
os.chdir(os.path.join("C:\\","test"))
for files in glob.glob("tsa*txt"):
    try:
        f=open(files)
    except Exception,e:
        print e
    else:
        filename = f.readline().strip().split()[0]
        f.close()
        newfilename = files[:5]+filename+".txt"
        try:
            os.rename(files,newfilename)
        except Exception,e:
            print e

save the above as myscript.py and on command line
c:\test> python myscript.py



Report •

#2
May 27, 2009 at 04:54:58
Sorry I don't have python installed.

I have tried to run a script which was there for a similar requirement on the forum, but could not getthe same.

The difference being, my txt file is tab delimited and the file has to be named useing the 1 column and not the 4th and the 5th.


Report •

Related Solutions


Ask Question