python 根据菜单对tar进行相关操作

本文介绍如何使用Python脚本打开并操作tar压缩包,包括提取文件、查看文件信息和列出所有文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#!/usr/bin/env python
import tarfile,sys
try:
    tar=tarfile.open(sys.argv[1],'r:tar')
	#sys.argv[1]为执行命令时输入的第1个参数,sysargv[0]为当前执行脚本路径与脚本名称;以读的模式读取tar包,tar变量包含压缩包所有文件及其属性
    selection=raw_input("Enter\n\
1 to extract a file\n\
2 to dispaly information on a file in the archive\n\
3 to list all the files in the archive\n\n")

    

    if selection=="1":
        filename=raw_input("Enter the filename to extract: ")
        tar.extract(filename)
		#解压某一个文件,extractall是解压所有文件,默认是解压到当前文件也可使用tar.extract(filename,path="/tmp")来指定路径
    elif selection=="2":
        filename=raw_input("Enter the filename to inspect: ")
        for tarinfo in tar:
            if tarinfo.name==filename:
			#对比到是想查的文件就将其打印出来,tar.getnames()获取压缩包里所有文件名称
                print "\n\
Filename:",tarinfo.name,"\n\
    Size:",tarinfo.size,"bytes"
    elif selection=="3":
        print tar.list(verbose=True)
		#verbose=True时,相当于ls -l,为False时只例出文件名。
	tar.close()
except:
    print "There was a problem running the program"



执行结果

[root@localhost tmp]# ./tar.py /root/test.tar
Enter
1 to extract a file
2 to dispaly information on a file in the archive
3 to list all the files in the archive

1
Enter the filename to extract: test/444.log



[root@localhost tmp]# ./tar.py /root/test.tar
Enter
1 to extract a file
2 to dispaly information on a file in the archive
3 to list all the files in the archive

2
Enter the filename to inspect: test/444.log

Filename: test/444.log
    Size: 7799 bytes
	
	

[root@localhost tmp]# ./tar.py /root/test.tar
Enter
1 to extract a file
2 to dispaly information on a file in the archive
3 to list all the files in the archive

3
-rwxr-xr-x root/root          0 2015-01-09 05:19:35 test/
-rw-r--r-- root/root       7799 2015-01-09 05:19:35 test/444.log
-rw-r--r-- root/root     167678 2015-01-09 05:19:35 test/333.txt
-rw-r--r-- root/root      10240 2015-01-09 05:19:35 test/2.py
None


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值