0

I have multiple files in various folders that look like this:

cat - dog - bark.docx

I want to bulk rename the files so that the string before the first hyphen is moved to the end of the filename:

dog - bark - cat.docx

Here’s what I’ve got so far:

import os
path = input(‘Copy and paste the location of the files.’)
for filename in os.listdir(path):
  filename_without_ext = os.path.splitext(filename)[0]
  extension = os.path.splitext(filename)[1]
  str_to_move = filename.split('-')[0]
  new_filename = filename_without_ext.split('-')[1:] + ' - '+ str_to_move + extension
  os.rename(os.path.join(path, filename), os.path.join(path, new_filename))

When I run the code it brings up the error message

‘TypeError: can only concatenate list (not "str") to list’. I’d be very grateful if someone could tell me what I’m doing wrong.

I’m new to coding and Python (as you can probably tell) so go easy on me.

Jignasha Royala
  • 1,032
  • 10
  • 27
Kat hughes
  • 55
  • 1
  • 6

3 Answers3

0

You're trying to concatenate a list with a string which does not work. Try replacing:

new_filename = filename_without_ext.split('-')[1:] + ' - '+ str_to_move + extension

with

new_filename = '-'.join(filename_without_ext.split('-')[1:]) + '-' + str_to_move + extension
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
0
import os
path = input(‘Copy and paste the location of the files.’)
for filename in os.listdir(path):
  filename_without_ext = os.path.splitext(filename)[0]
  extension = os.path.splitext(filename)[1]
  parts_of_filename = filename_without_ext.split(' - ')
  new_filename = parts_of_filename[1] + ' - '+ parts_of_filename[2] + ' - ' + parts_of_filename[0] + extension
  os.rename(os.path.join(path, filename), os.path.join(path, new_filename))
Atirag
  • 1,660
  • 7
  • 32
  • 60
0

Your problem is this line:

new_filename = filename_without_ext.split('-')[1:] + ' - '+ str_to_move + extension

You're trying to concatenate a string to a list. The assumption you're making is that each element of the list would be added together before your next statement. The code is ambiguous as you could either want that or you could want to add your substring to each element of the list.

You want to use join as this answer said.

So:

'-'.join(filename_without_ext.split('-')[1:])

Though you still have the leading space on your first entry to worry about. So you might want to split by ' - ' instead.

Tim Bradley
  • 173
  • 6