0

This is the code:

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'

I am getting output as:

['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"']

The two lists are identical except the white space between two entries of the first list. Because of that, the comparison is giving false value. How to remove that white space? Please help. Thank you in advance.

Gung Foo
  • 13,392
  • 5
  • 31
  • 39
manali23
  • 19
  • 2
  • 6

1 Answers1

0

You are stripping empty lines; skip them with a simple if:

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

You can simplify those lines with a list comprehension:

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

(no need to use desired_setting = list() before these lines now).

Alternatively, filter the lines after the fact:

desired_setting = filter(None, desired_setting)

or

desired_setting = [line for line in desired_setting if line]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • You might want to think about not doing the `.strip()` action twice. Imperative version can use a variable, but doing this in the functional version (list comprehension) is tricky. – Alfe May 28 '13 at 07:56
  • @Alfe: In the list comprehension, that is going to be tricky, and not worth it really. – Martijn Pieters May 28 '13 at 07:57
  • Yeah; the missing `let` of Python ;-) One could use sth like `desired_setting = [strippedLine for line in f for strippedLine in [line.strip()] if strippedLine]`, but that's a hack. – Alfe May 28 '13 at 07:59
  • 1
    Exactly; I was trying to minimise the difference between the loop and the list comp here. – Martijn Pieters May 28 '13 at 08:01