Removing specific numbers and character from name string

Viewed 55

I have a python function that pulls all my .md files from a folder and turns them all into html files while also making one big markdown file.

import glob
import os
import markdown

def main():
    file_list_md = glob.glob(os.path.join("\\\\servermame\\prod_help_file\\input\\*", "*.md"))
    file_list_html = glob.glob(os.path.join("\\\\servername\\prod_help_file\\input\\*", "*.html"))
    config = {
        'extra': {
            'footnotes': {
                'UNIQUE_IDS': True
            }
        }
    }
    with open('\\\\servername\\prod_help_file\\bigfile.md', 'w') as output:
        for x in file_list_md:
            with open(x, 'r') as body:
                text = body.read()
                html = markdown.markdown(text, extensions=['extra'], extension_configs=config)
                output.write(html)
                y = x.replace('input', 'output')
                k = y.replace('.md', '.html')
                with open(k, 'w') as output2:
                    with open(file_list_html[0], 'r') as head:
                        text = head.read()
                        output2.write(text)
                        output2.write(html)
                    with open(file_list_html[1], 'r') as foot:
                        text = foot.read()
                        output2.write(text)

if __name__ == "__main__":
    main()

but I have to use the full directory and to keep them in order the files have 5 numbers and an underscore like this:

"C:\\servername\prod_help_file\input\10809_file.md"

and I want the output file to be like this:

"C:\\servername\prod_help_file\output\file.md" 

without the numbers or underscore. is there any ways to remove the 5 numbers and underscore only?

3 Answers

you can use re module

import re    
re.sub(r'\d\d\d\d\d_','','19345_file.md')
# file.md
import re

txt = "The rain 85452_in Spain"
x = re.sub(r"\d{5}_", "", txt) # Subtitute 5 digits of number with underscore with empty string

if underscore always exists then you can do like this:

import os
path = '/my/path_1222/10809_file.md'
dir = os.path.dirname(path)
file = os.path.basename(path)
file = file.split('_', 1)[1]
f = os.path.join(dir, file)
Related