Split pathname in python
Question:
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?
Answers:
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
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
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?
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
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