编写一个程序demo.py,要求运行该程序后,生成demo_new.py 文件,其中内容与demo.py 一样,只是在每一行的后面加上行号。要求行号以#开始,并且所有行的#符号垂直对齐。 2、编写程序,实现磁盘垃圾文件清理功能。要求程序运行时,通过命令行参数指定要清理的文件夹,然后删除该文件夹及其子文件夹中所有扩展名为tmp、log、obj、txt 以及大小为0 的文件。
时间: 2024-02-03 19:14:15 浏览: 71
py代码-python代码demo
1. 生成带行号的新文件demo_new.py:
```python
with open("demo.py", "r") as f:
lines = f.readlines()
with open("demo_new.py", "w") as f:
for i, line in enumerate(lines):
f.write(f"{line.strip()} #{i+1}\n")
```
2. 实现磁盘垃圾文件清理功能:
```python
import os
import sys
def clean_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
file_size = os.path.getsize(file_path)
file_ext = os.path.splitext(file_path)[1]
if (file_size == 0) or (file_ext in [".tmp", ".log", ".obj", ".txt"]):
os.remove(file_path)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python clean.py folder_path")
else:
folder_path = sys.argv[1]
if not os.path.exists(folder_path):
print(f"Folder {folder_path} does not exist.")
else:
clean_folder(folder_path)
print(f"Folder {folder_path} has been cleaned.")
```
可以通过命令行运行该程序,并指定要清理的文件夹路径,例如:
```
python clean.py /path/to/folder
```
阅读全文