1

I made python_learning_notes in separated chapters saved as '.md' file like:

  1. data-type.md
  2. data-structure.md
  3. high-level-data-structure.md
  4. code-structure.md
  5. object-oriented-programing.md

I copied the contents of each files and pasted them in a single '.md' file.

The job is done in ugly 7 steps and I want to refactor the codes more handy.

  1. change to the destination directory
  2. get and validate the '.md' filename
  3. rename '.md' to '.txt'
  4. read contents from '.txt' to a list
  5. write to a single '.txt' filename
  6. rename the single '.txt' file to '.md'
  7. restore all the '.txt' to '.md'

Here is my code:

# 1.change to the destination directory
path_name = ' ~/Documents/'
os.chdir(path_name)

# 2.get and validate the '.md' filename
x = os.dirlist(path_name)
qualified_filenames = [i for i in x if '.md' is in x]

# 3.rename '.md' to '.txt'
new_names = []
for i in qualified_filenames:
    name,extension = os.path.splitext(i)
    extension = '.txt'
    new_name = '{}{}'.format(name, extension)
    os.rename(i, new_name)
    new_names.append(new_name)

# 4.read contents from '.txt' to a list
contents_list = []
for i in new_names:
    with open(i) as fp:
        line = fp.read(i)
        contents_list.append(line)

# 5.write to a single '.txt' filename
with open('single-file.txt','w') as fp:
    for i in contents_list:
        fp.write(i + '\n')

# 6.rename the single '.txt' file to '.md'
os.rename('single-file.txt','single-file.md')

# 7.restore all the '.txt' to '.md'
for i, j in zip(new_names, qualified_filenames):
    os.rename(i, j)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

3

This would be a bit shorter:

import glob
import fileinput
import os

pat = os.path.expanduser('~/Documents/*.md')
with open('single-file.md', 'w') as fout:
    for line in sorted(fileinput.input(glob.glob(pat))):
        fout.write(line)
Mike Müller
  • 82,630
  • 20
  • 166
  • 161