使用python将数据从外部文件保存到列表中

时间:2013-03-12 09:09:36

标签: python linux

这个问题可能会重演;但这里的代码将解释这个问题:

#compares partitions displayed by 'df' command with the required list of partitions.

import subprocess
import re


p = subprocess.Popen("df -h", stdout=subprocess.PIPE, shell=True)
dfdata, _ = p.communicate()

dfdata = dfdata.replace("Mounted on", "")

columns = [list() for i in range(10)]
for line in dfdata.split("\n"):
    line = re.sub(" +", " ", line)
    for i,l in enumerate(line.split(" ")):
        columns[i].append(l)


sys_partition = columns[5]
req_partition = ['/', '/boot', '/home', '/usr', '/usr/local', '/var', '/tmp', '/mnt/floppy', '/mnt/cdrom', '/dev/shm']


def remove_common_elements(sys_partition, req_partition):
    sys_partition_new = sys_partition[:]
    req_partition_new = req_partition[:]

    for i in sys_partition:
        if i in req_partition_new:
            sys_partition_new.remove(i)
            req_partition_new.remove(i)
return req_partition_new

if set(sys_partition) == set(req_partition):
    print 'All the partitions exist in your system!!!'
else:
    print 'These partitions do not exist: ',
    print (remove_common_elements(sys_partition, req_partition))

在此程序中,'sys_partition'表示系统中存在的分区(由df命令显示),'req_partition'表示理想情况下应存在的分区列表。现在,我不想硬编码所需的分区(req_partition)。我想从一些外部文件中获取该输入并将其存储到列表中,然后如图所示进行处理。 请帮忙。如果问题令人困惑,我会尝试详细说明。 提前致谢

1 个答案:

答案 0 :(得分:0)

看起来您正在询问如何从文件中读取数据,并将这些项目放在列表中。如果是这样,请删除此行:

req_partition = ['/', '/boot', '/home', '/usr', '/usr/local', '/var', '/tmp',    '/mnt/floppy', '/mnt/cdrom', '/dev/shm']

将其替换为以下行:

req_partition = list()
with open('/path/to/partitions') as f:
    for line in f:
        req_partition.append(line.strip())

确保文件/path/to/partitions包含以下内容:

/
/boot
/home
/usr
/usr/local
/var
/tmp
/mnt/floppy
/mnt/cdrom
/dev/shm