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

标签 python

我在单独的章节中制作了 python_learning_notes 并保存为“.md”文件,例如:

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

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

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

  1. 更改为目标目录
  2. 获取并验证“.md”文件名
  3. 将“.md”重命名为“.txt”
  4. 将“.txt”中的内容读取到列表
  5. 写入单个“.txt”文件名
  6. 将单个“.txt”文件重命名为“.md”
  7. 将所有“.txt”恢复为“.md”

这是我的代码:

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

最佳答案

这会更短一点:

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)

关于python - 如何以优雅的Pythonic方式更有效地组合多个 '.md'文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537863/

相关文章:

python - 旋转 SQLite 表,像 SQL 一样应该是

python - 显示之前创建的 pandas 绘图

python - 将 python session 传递给用另一个版本的 python 编写的脚本

python - 回滚后 SQLAlchemy 恢复 "This transaction is inactive"

python - Django模型的clean方法多次报错

python - 使用动态键创建 pydantic 模型

Python套接字错误TypeError : a bytes-like object is required, not 'str' with send function

python - Wx.Widgets AUIMananger 切换 Pane

python - 如何在 Pandas 中组合文本行

php - 如何检查 python 脚本 (test.py) 是否在 Windows 10 上运行