使用Python比较目录和文本文件

2024-06-13 00:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是比较两个数据,一个来自文本文件,另一个来自目录,比较后,控制台将通知或显示未找到的数据,例如:

ls: /var/patchbundle/rpms/:squid-2.6.STABLE21-7.el5_10.x86_64.rpm NOT FOUND!
ls: /var/patchbundle/rpms/:tzdata-2014j-1.el5.x86_64.rpm 
ls: /var/patchbundle/rpms/:tzdata-java-2014j-1.el5.x86_64.rpm 
ls: /var/patchbundle/rpms/:wireshark-1.0.15-7.el5_11.x86_64.rpm
ls: /var/patchbundle/rpms/:wireshark-gnome-1.0.15-7.el5_11.x86_64.rpm 
ls: /var/patchbundle/rpms/:yum-updatesd-0.9-6.el5_10.noarch.rpm NOT FOUND

一定是这样的。下面是我的python代码。你知道吗

import package, sys, os, subprocess

path = '/var/tools/tools/newrpms.txt'

newrpms = open(path, "r")
fds = newrpms.readline()
def checkrc(rc):
            if(rc != 0):
                    sys.exit(rc)
cmd = package.Errata()
for i in newrpms:
    rc = cmd.execute("ls /var/patchbundle/rpms/ | grep %newrpms ")
        if ( != 0):
                    cmd.logprint ("%s not found !" % i)
checkrc(rc)
sys.exit(0)
newrpms.close

请看shell脚本。这个脚本是它的执行文件,但因为我想使用另一种语言,所以我尝试python

retval=0
for i in $(cat /var/tools/tools/newrpms.txt)
do
        ls /var/patchbundle/rpms/ | grep $i
        if [ $? != 0 ]
        then
                echo "$i NOT FOUND!"
                retval=255
        fi
done
exit $retval

请看我的Python代码。什么是错误的,因为它不像shell那样执行它。你知道吗


Tags: ifvarsysexitnottoolslsx86
1条回答
网友
1楼 · 发布于 2024-06-13 00:30:43

你不说什么“的内容”newrpms.txt文件“是;你说脚本没有按你想要的方式执行-但是你没有说它在做什么;我不知道packagepackage.Errata是什么,所以我在玩猜谜游戏;但是很多事情都错了。你知道吗

  1. if ( != 0):是一个语法错误。如果{empty space}不等于零?

  2. cmd.execute("ls /var/patchbundle/rpms/ | grep %newrpms ")可能不是你想做的。在Python中不能像那样将变量放入字符串中,如果可以的话newrpms是文件句柄而不是当前行。那应该是...grep %s" % (i,))

  3. 控制流正在执行:

    1. 查找此文件夹,尝试查找文件
    2. 调用checkrc()
    3. 只有在找不到最后一个文件时才退出并出现错误
  4. newrpms.close没有做任何事情,需要newrpms.close()才能调用close方法。

你在用Python写shell脚本。怎么样:

import os, sys

retval=0

for line in open('/var/tools/tools/newrpms.txt'):
    rpm_path = '/var/patchbundle/rpms/' + line.strip()
    if not os.path.exists(rpm_path):
        print rpm_path, "NOT FOUND"
        retval = 255
    else:
        print rpm_path

sys.exit(retval)

略加编辑代码,并给出说明:

代码几乎是shell脚本到Python的直接副本。它在文本文件中的每一行上循环,并调用line.strip()以除去末尾的换行符。它构建rpm_path,类似于“/var/patchbundle/rpms/:tzdata-2014j-1.el5.x86\u 64.rpm”。你知道吗

然后它使用sys.path.exists()测试文件是否存在,如果存在则返回True,如果不存在则返回False,并使用该测试设置错误值并打印结果,就像shell脚本打印结果一样。这取代了“ls。。。|grep“用于检查文件是否存在的代码的一部分。你知道吗

相关问题 更多 >