首页 > 解决方案 > Python:编译、重命名和移动

问题描述

好的,所以我有一个 Python 项目。我制作了一个批处理文件来编译所有.py文件。编译后我想:

我已经编译了 .py 文件(python -m compileall -f C:\Pejo\ ),但是我该如何完成剩下的任务呢?

我认为它应该是这样的:

for /R C:\Pejo\ %%G in (*.py *.pyc) do (...)

但我不知道如何继续。

标签: python

解决方案


- 删除所有 .py 文件(编译后我不再需要它们);

import os
import shutils

for file in os.listdir('path-to-files'):
    if file.endswith('.py'):
        os.remove(os.path.join('path-to-file', file)

找到所有 .pyc 文件并重命名它们(例如:game.cpython-36.pyc 应该重命名为 game.pyc...

for file in os.listdir('path-to-files'):
    if file.endswith('.pyc'):
        newName = file.split(".")[0] +'.' + file.split(".")[-1]
        os.rename(os.path.join('path-to-file', file),os.path.join('path-to-file', newName)
        shutils.move(os.path.join('path-to-file', newName),os.path.join('../', 'path_to_file'))

查找编译后创建的所有 pycache 文件夹

for folders in os.listdir('path-to-folders'):
    if folders.startswith('pycache'):
        os.rmdir(os.path.join('path-to-file', folder)

推荐阅读