首页 > 解决方案 > 如何根据特定文件夹中的文件创建文件夹

问题描述

我有一个包含几个 pdf 和 word 文件的文件夹。我想根据我之前阅读的文件创建一个新文件夹,我想要子文件夹,每个子文件夹应该有 3 个空白文本文件让我们说 test1.txt, test2.txt,test.txt 我是 python 新手,请帮助....

标签: pythonpandastextdirectorymkdir

解决方案


from pathlib import Path

files = Path().iterdir()

for file in files:
    new_file_path = Path(f'./{file.stem}')
    new_file_path.mkdir(parents=True, exist_ok=True)

    for i in range(3):
        p = new_file_path / f'{i + 1}.txt'
        with p.open('w') as nf:
             nf.write('')

one.doc我在目录中运行此脚本,例如,我有two.docthree.pdf。之后我得到下一个:

one/
    1.txt
    2.txt
    3.txt
two/
    1.txt
    2.txt
    3.txt
three/
    1.txt
    2.txt
    3.txt
one.doc
two.doc
three.pdf

我希望,您能够删除未使用的文件。


推荐阅读