首页 > 解决方案 > python:将文本与文件进行比较

问题描述

我想使用 python 将 shell 命令输出与文本文件进行比较,这是我的代码:

   os.system('find / -perm -u=s -type f 2>/dev/null')
   suid_file = open("suid_list.txt", "r")
   os.system('find / -perm -u=s -type f 2>/dev/null > /tmp/test1.txt')

   lines = suid_file.read().split(',')
   lines2 = open('/tmp/test1.txt', 'r').read()
   for y in lines:
       if y in lines2:
         #matched

test1.txt 的内容是:

/usr/bin/su
/usr/bin/bwrap
/usr/bin/chsh
/usr/bin/ntfs-3g
/usr/bin/kismet_cap_ti_cc_2540
/usr/bin/mount
/usr/bin/vmware-user-suid-wrapper
/usr/bin/passwd
/usr/bin/fusermount3
/usr/bin/kismet_cap_linux_bluetooth
/usr/bin/kismet_cap_nxp_kw41z
/usr/bin/kismet_cap_nrf_mousejack
/usr/bin/newgrp
/usr/bin/gpasswd

标签: pythonpython-3.xfilecompare

解决方案


   lines2 = file_read.read()

file_read.read() 的第二次调用将返回空。您应该在循环外部调用并将结果存储在一个可以在循环内部使用的变量中。


推荐阅读