python - Python:编译、重命名和移动
问题描述
好的,所以我有一个 Python 项目。我制作了一个批处理文件来编译所有.py文件。编译后我想:
删除所有.py文件(编译后我不再需要它们);
找到所有.pyc文件并重命名它们(例如:game.cpython-36.pyc应该重命名为game.pyc ...所以我只想从所有.pyc文件名中删除“.cpython-36”部分)和之后将它们上移一层(文件夹)(其中.py文件的初始位置);
找到编译后创建的所有pycache文件夹,现在应该是空的(因为我们已经在上面的步骤中移动了 .pyc 文件)并删除它们。
我已经编译了 .py 文件(python -m compileall -f C:\Pejo\
),但是我该如何完成剩下的任务呢?
我认为它应该是这样的:
for /R C:\Pejo\ %%G in (*.py *.pyc) do (...)
但我不知道如何继续。
解决方案
- 删除所有 .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)
推荐阅读
- java - 如何从我的 EditText 获取带有格式化日期的日期对象(通过 Spinner 存储)
- javascript - 如何避免 componentDidCatch() 多次触发某些东西?
- vue.js - 是否可以使用单文件组件制作可分发的 Vue 小部件?
- android - Android h3:六边形分层地理空间索引系统
- sql-server - 使用 vs2017 在 React 上的 onClick 事件中从 SQL Server 数据库获取数据
- c# - ASP.NET MVC Mulitlingual site not working properly
- wpf - WPF DataGrid 标题列有额外的边框
- http - HTTP 方法:为什么不总是使用 PUT 而不是 POST?
- oracle - 创建游标以连接到远程数据库
- java - 自定义 Web 项目的 Gradle 脚本