-1

I'm trying to rename a filename with python. the thing is, the filename has a specific amount of characters, 48 to be exactly, and i need to split this name into some variables, like split the file name into 10 characters, then into 20, then 16 and finally into 2.

ex. from 111111111122222222222222222222333333333333333344.txt to 22222222222222222244.txt

for file in os.listdir(folder):
    file_name, file_ext = os.path.splitext(file)

now, how could be split the file_name into those variables?

Prado
  • 3
  • 2
  • Splitting the filename into those 4 parts, considering the length , I need to get the second and the fourth parts. So the first part starts in character 1 and stops at character 10. The second part starts at 11 and goes until 30. – Prado Sep 26 '22 at 05:25
  • "So the first part starts in character 1 and stops at character 10..." That's exacty what slices are good for. – Code-Apprentice Sep 26 '22 at 05:25
  • 1
    This is not question speficic to filenames. What you are essentially doing is splitting a string. – Niko Föhr Sep 26 '22 at 05:33

2 Answers2

1

You can split via simple indexing I think, but don't see any pattern to split at those nos though... maybe try this then...

file = "111111111122222222222222222222333333333333333344.txt"
file_name = file[11:31] + file[-6:-4]
file_ext = file[-4:]

print(file_name)
print(file_ext)

# Output
2222222222222222222344
.txt
Sachin Kohli
  • 1,956
  • 1
  • 1
  • 6
0
import re
fileName = "111111111122222222222222222222333333333333333344.txt"

#This will return 5 groups from the regex:

fileNameGroups = re.match("(.{10})(.{20})(.{16})(.{2})(.*)",fileName).groups()
print(fileNameGroups)
#with `format` you can construct the new file name
newFileName = "{}{}{}".format(fileNameGroups[1],fileNameGroups[3],fileNameGroups[4])
print(newFileName)


# Output
('1111111111', '22222222222222222222', '3333333333333333', '44', '.txt')
2222222222222222222244.txt
A. Herlas
  • 173
  • 9