如何以优雅的pythonic方式更有效地组合多个'.md'文件?

时间:2017-08-07 00:16:37

标签: python

我在分开的章节中创建了python_learning_notes,保存为'.md'文件,如:

  
      
  1. data-type.md
  2.   
  3. data-structure.md
  4.   
  5. high-level-data-structure.md
  6.   
  7. code-structure.md
  8.   
  9. object-oriented-programing.md
  10.   

我复制了每个文件的内容,并将它们粘贴在一个“.md”文件中。

这项工作以丑陋的7个步骤完成,我想更加方便地重构代码。

  1. 更改为目标目录
  2. 获取并验证'.md'文件名
  3. 将'.md'重命名为'.txt'
  4. 将内容从“.txt”读取到列表
  5. 写一个'.txt'文件名
  6. 将单个“.txt”文件重命名为“.md”
  7. 将所有'.txt'恢复为'.md'
  8. 这是我的代码:

    # 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)
    

1 个答案:

答案 0 :(得分:1)

这会有点短:

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)