Opening files found from os.listdir() and comparin

2019-09-06 17:24发布

Alright, so I'm writing a program to help connect to wireless networks. I have most of it down (in fact, it's complete. I'm just working on extra features.)

I'm writing a GUI frontend for a wireless network connection backend called NetCTL for the Arch Linux Operating System. Basically, people can manually create profiles and name it whatever they want (i.e., "asdfasdfasdf"), but mine will ALWAYS generate $NetworkSSID_wifiz.

However, every file will have one line in it that would be able to determine if it is for the same network.

The line is:

ESSID='$NetworkSSID'

So how would I go about opening each file that appears in os.listdir and checking if those two files have the same line (while not producing too much overhead, preferably.)?

All profiles are saved in /etc/netctl whether generated by my program, or by the user.

Sample files:

User Created:

Description='A simple WPA encrypted wireless connection'
Interface=wlp2s0
Connection=wireless
Security=wpa

IP=dhcp

ESSID='MomAndKids'
# Prepend hexadecimal keys with \"
# If your key starts with ", write it as '""<key>"'
# See also: the section on special quoting rules in netctl.profile(5)
Key='########'
# Uncomment this if your ssid is hidden
#Hidden=yes

Created by my program:

Description='A profile generated by WiFiz for MomAndKids'
Interface=wlp2s0
Connection=wireless
Security=wpa
ESSID='MomAndKids'
Key='#######'
IP=dhcp

Sample os.listdir output:

['hooks', 'interfaces', 'examples', 'ddwrt', 'MomAndKids_wifiz', 'backups', 'MomAndKids']

标签: python linux
2条回答
男人必须洒脱
2楼-- · 2019-09-06 18:11

This should work for you:

from glob import glob
from os import path

config_dir = '/etc/netctl'

profiles = dict((i, {'full_path': v, 'ESSID': None, 'matches': []}) for (i, v) in enumerate(glob(config_dir + '/*')) if path.isfile(v))

for K, V in profiles.items():
    with open(V['full_path']) as f:
        for line in f:
            if line.startswith('ESSID'):
                V['ESSID'] = line.split('=',1)[1].strip()
                break # no need to keep reading.
    for k, v in profiles.items():
        if K == k or k in V['matches'] or not v['ESSID']:
            continue
        if V['ESSID'] == v['ESSID']:
            V['matches'].append(k)
            v['matches'].append(K)

for k, v in profiles.items():
    print k, v
查看更多
趁早两清
3楼-- · 2019-09-06 18:15
import os

all_essid = []

for file in os.listdir('.'):

    if not os.path.isfile(file):
        break

    with open(file) as fo:
        file_lines = fo.readlines()

    for line in file_lines:

        if line.startswith('ESSID')

            if line in all_essid:
                print 'duplicate essid %s' % line

            all_essid.append(line)

Or you could try os.walk if you want to descend into the directories;

    for root, dirs, files in os.walk("."):

        for file in files:

             # etc.
查看更多
登录 后发表回答