Reputation: 3
1.st step: underscore to space
path = os.getcwd()
filenames = os.listdir(path)
for filename in filenames:
os.rename(os.path.join(path,filename),os.path.join(path, filename.replace("_", " ")))
OUTCOME:
(cant post picture yet.. so:)
WKN_855681(INTEL_CORP._______DL-001)_vom_03.12.2018482523.pdf
Geändert auf: (changed to)
WKN 855681(INTEL CORP. DL-001) vom 03.12.2018482523.pdf
!This is fine :D
now i like to delete the surplus spaces in the (changed to) state.
PS: im a bloody rookie so please dont kill me yet.
ty
Outcome, I think the text here doesn't show the spaces..?
Upvotes: 0
Views: 289
Reputation: 8273
Use regex to replace the surplus spaces to just one
import re
re.sub('\s{1,}',' ',file)
Test
a='WKN 855681(INTEL CORP. DL-001) vom 03.12.2018482523.pdf'
output
'WKN 855681(INTEL CORP. DL-001) vom 03.12.2018482523.pdf'
Or in a single step replace surplus _
with just one space
re.sub('\_{1,}',' ',file)
Test
a='WKN_855681(INTEL_CORP._______DL-001)_vom_03.12.2018482523.pdf'
re.sub('\_{1,}',' ',a)
Output
'WKN 855681(INTEL CORP. DL-001) vom 03.12.2018482523.pdf'
Upvotes: 1
Reputation: 42758
Use regular expression:
import re
os.rename(os.path.join(path, filename), os.path.join(path, re.sub('[\s_]+', ' ', filename))
Upvotes: 1
Reputation: 98921
My 2c using glob
, re.sub
and os.rename
:
import glob, os, re
for fn in glob.glob('C:\\somedir\\*'):
new_fn = re.sub(" ", "_")
os.rename(fn, new_fn)
Upvotes: 0