0

这是代码:

import os
import re
import subprocess

current_setting = list()
with open('/etc/init/control-alt-delete.conf' ,'r')as fp:
    for line in fp:
        if not line.startswith('#'):
            current_setting.append(line.strip())
current_setting.remove('')
print current_setting

desired_setting = list()
with open('ctl_alt_del', 'r') as f:
    for line in f:
        desired_setting.append(line.strip())
print desired_setting

if set(current_setting) == set(desired_setting):
    print 'The file has to be modified'

我得到的输出为:

['start on control-alt-delete', '', 'exec /sbin/shutdown -r now "Control-Alt-Delete pressed"']
['start on control-alt-delete', 'exec /sbin/shutdown -r now "Control-Alt-Delete pressed"']

除了第一个列表的两个条目之间的空白之外,这两个列表是相同的。因此,比较给出了错误的值。如何删除那个空白?请帮忙。先感谢您。

4

1 回答 1

0

您正在剥离空行;用一个简单的方法跳过它们if

with open('ctl_alt_del', 'r') as f:
    for line in f:
        if line.strip():
            desired_setting.append(line.strip())

您可以使用列表理解来简化这些行:

with open('ctl_alt_del', 'r') as f:
    desired_setting = [line.strip() for line in f if line.strip()]

(现在不需要desired_setting = list()在这些行之前使用)。

或者,在事后过滤行:

desired_setting = filter(None, desired_setting)

或者

desired_setting = [line for line in desired_setting if line]
于 2013-05-28T07:47:32.353 回答