编写脚本exe1,该脚本接收一个命令行参数,并根据其类型做以下操作: • 若参数为普通文件,则显示其内容 • 若参数为压缩文件,则解压缩(如同目录下有同名文件则放弃) • 若参数为目录,则将其归档并压缩(如已有同名压缩文件则放弃) • 若参数不存在,给出错误提示并退出
时间: 2024-10-16 22:15:09 浏览: 28
编写一个名为 `exe1.py` 的Python脚本,可以实现这个功能。这里是一个基本的示例:
```python
import os
import zipfile
import argparse
def read_file(file_path):
with open(file_path, 'r') as f:
return f.read()
def extract_zip(file_path, target_dir=None):
try:
with zipfile.ZipFile(file_path, 'r') as zip_ref:
if not target_dir:
target_dir = os.path.splitext(os.path.basename(file_path))[0]
if os.path.exists(target_dir):
print(f"Directory {target_dir} already exists, skipping extraction.")
else:
zip_ref.extractall(target_dir)
except zipfile.BadZipFile:
print(f"{file_path} is not a valid ZIP file.")
def compress_directory(directory_path, archive_name=None):
try:
if not archive_name:
archive_name = os.path.basename(directory_path) + ".zip"
with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(directory_path):
for file in files:
zipf.write(os.path.join(root, file))
except Exception as e:
print(f"Error compressing directory: {e}")
def main():
parser = argparse.ArgumentParser(description='Process command line arguments.')
parser.add_argument('input', type=str, help='The input file or directory')
args = parser.parse_args()
input_path = args.input
if os.path.isfile(input_path):
print("Checking file content...")
print(read_file(input_path))
elif os.path.isdir(input_path):
print("Compressing directory...")
compress_directory(input_path)
elif os.path.splitext(input_path)[1] in ['.zip', '.gz', '.rar']: # Assuming common compression formats
print("Extracting compressed file...")
extract_zip(input_path)
else:
print(f"Invalid input: {input_path}. Please provide a file, directory, or a recognized compressed file.")
if __name__ == "__main__":
main()
```
运行此脚本时,你可以通过命令行传入参数,例如:
```bash
python exe1.py /path/to/file.txt
python exe1.py /path/to/compressed.zip
python exe1.py /path/to/directory/
```
阅读全文