Maverick Maverick - 3 years ago 153
Python Question

Strip text from files after first space

I'm trying to rename about a few thousand files to just have their code, files are named like this:


2834 The file

2312 The file

982 The file


Desired output:


2834

2312

982


The code I want to rename them to is separated by a space, so I just need to strip the text after the space.

I have tried using os/glob/enumerate just to rename in them in numerical order, which is proving problematic as the directory is not being returned in the same order, so when I rename them the codes are mixed up.

Answer Source

You'll want to use glob and os. A simple example (with comments), is as follows:

import glob
import os

# iterate over all the files
for files in glob.glob('*.*'):
    try:
        new = files.replace("The file", '') # if there's a match replace names
        os.rename(files, new) # rename the file
        print files, new # just to make sure it's working
    except:
        print 'ERROR!!,', files # to see if there were any errors

Alternatively, if the the code is always the first 4 characters, you could do the following:

import glob
import os

# iterate over all the files
for files in glob.glob('*.*'):
    try:
        os.rename(files, files[0:4]) # rename the file
        print files, new # just to make sure it's working
    except:
        print 'ERROR!!,', files # to see if there were any errors

Just noticed one of your examples only has 3 characters as the code. A better solution might be using .find(' ') on the file name to locate the space ready for the string slice. For example:

import glob
import os

# iterate over all the files
for files in glob.glob('*.*'):
    try:
        os.rename(files, files[0: files.find(' ')]) # rename the file
        print files # just to make sure it's working
    except:
        print 'ERROR!!,', files # to see if there were any errors
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download