SPSS Tutorials

BASICS REGRESSION T-TEST ANOVA CORRELATION

Rename or Prefix Many Files

Question

"I have a number of data files with incomprehensible file names. In order to keep track of these, I'd like to prefix their file names or perhaps even rename them to some prefix + constant. What would be the easiest way to do so?"

SPSS Python Syntax Example

*1. Create test data files.

begin program.
rdir = 'd:/temp/' #Please specify an empty test folder.
import spss,random
while len(os.listdir(rdir))<10:
    fnlen = random.randrange(3,8)
    fn = ''
    for char in range(fnlen):
        fn += chr(random.randrange(97,123))
    if not rdir + fn + '.sav' in os.listdir(rdir):
        spss.Submit('data list free/id.\nbegin data\n1\nend data.\nsav out "%(rdir)s%(fn)s.sav".'%locals())
spss.Submit('new file.')
end program.


*2. Prefix names of all .sav files in rdir.

begin program.
rdir = 'd:/temp/' #Please specify folder containing relevant data files.
for num,fil in enumerate([fil for fil in os.listdir(rdir) if fil.endswith('.sav')]):
    os.rename(rdir + fil,rdir + str(num+1).zfill(3) + '_' + fil)
end program.

Description

Alternatively, Discarding Old File Names

"Actually, the file names don't make any sense whatsoever. Can't I just rename them to some root name (say, "file_") with a suffix?"

SPSS Python Syntax Example

begin program.
rdir = 'd:/temp/' # Specify the folder containing all relevant files.
rootname = 'file_' # Specify a root for the new file names.
for num,fil in enumerate([fil for fil in os.listdir(rdir) if fil.endswith('.sav')]):
    os.rename(rdir + fil,rdir + rootname + str(num + 1).zfill(3) + '.sav')
end program.

Description

Previous tutorial: Export Output to Different Folders

Next tutorial: Search Syntax Files for Expression

Let me know what you think!

*Required field. Your comment will show up after approval from a moderator.