0

I'm a bit new to Python and I am trying to simplify my existing code. Right now, I have the code repeated 5 times with different strings. I'd like to have the code one time and have it run through a list of strings.

Currently what I have:

def wiScanFormat():

    File = open("/home/pi/gpsMaster/WiScan.txt", "r")
    data = File.read()
    File.close()
    MAC = data.replace("Address:", "\nAddress, ")
    File = open("/home/pi/gpsMaster/WiScan.txt", "w")
    File.write(MAC)
    File.close()

    File = open("/home/pi/gpsMaster/WiScan.txt", "r")
    data = File.read()
    File.close()
    SSID = data.replace("ESSID:", "\nESSID, ")
    File = open("/home/pi/gpsMaster/WiScan.txt", "w")
    File.write(SSID)
    File.close()

    File = open("/home/pi/gpsMaster/WiScan.txt", "r")
    data = File.read()
    File.close()
    FREQ = data.replace("Frequency:", "\nFrequency, ")
    File = open("/home/pi/gpsMaster/WiScan.txt", "w")
    File.write(FREQ)
    File.close()

    File = open("/home/pi/gpsMaster/WiScan.txt", "r")
    data = File.read()
    File.close()
    QUAL = data.replace("Quality", "\nQuality, ")
    File = open("/home/pi/gpsMaster/WiScan.txt", "w")
    File.write(QUAL)
    File.close()

    File = open("/home/pi/gpsMaster/WiScan.txt", "r")
    data = File.read()
    File.close()
    SIG = data.replace("Signal level", "\nSignal Level, ")
    File = open("/home/pi/gpsMaster/WiScan.txt", "w")
    File.write(SIG)
    File.close()

What I'd like to have:

ORG = ['Address:', 'ESSID:'...etc]
NEW = ['\nAddress, ' , '\nESSID, ' , ...  etc]

and run that through:

    File = open("/home/pi/gpsMaster/WiScan.txt", "r")
    data = File.read()
    File.close()
    ID = data.replace("ORG", "NEW")
    File = open("/home/pi/gpsMaster/WiScan.txt", "w")
    File.write(ID)
    File.close()

I've tried running exactly what I put up, but it does not seem to format it the way I need to.

The output from above looks like:

Cell 46 - Address: xx:xx:xx:xx:xx:xx    ESSID:"MySSID"  Frequency:2.412 GHz (Channel 1) Quality=47/100  Signal level=48/100 Quality=47/100  Signal level=48/100

But it is supposed to look like this (And it does when I run that same block over the strings separately):

xx:xx:xx:xx:xx:xx   MySSID  5.18 GHz (Channel 36)   0.81    0.99

How should I go about looping this block of code through my list of strings? There two strings that I would need for the find and replace, old and new, so they would have to work together. These lists will be the same size, obviously, and I need them to be in the correct order. Address with address, ESSID with ESSID, etc.

Thanks in advance!

4
  • 1
    Are you genuinely opening the same file five times to perform a sequence of different edits on it, or have I misunderstood? Commented Apr 12, 2016 at 13:12
  • @khelwood Yes, currently I am. I'm aware this isn't the most efficient way to go about this which is why I am exploring other options edit: actually, its being open 10 times. 5 for reads, 5 for writes Commented Apr 12, 2016 at 13:15
  • 1. replace only replace the first match if I remember correctly. Use re.sub instead. 2. use with open("..") as f: # do something instead of f = open("..") and f.close. 3. post your formatted example data! Commented Apr 12, 2016 at 13:18
  • 1
    @knh170: str.replace defaults to replacing all instances, not one, it takes an argument to limit replacements. Don't push people to regular expressions for simple replacement operations, this isn't Perl! :-) Commented Apr 12, 2016 at 13:22

4 Answers 4

1

Try something like this:

ORG = ['Address:', 'ESSID:'...etc]
NEW = ['\nAddress, ' , '\nESSID, ' , ...  etc]

File = open("/home/pi/gpsMaster/WiScan.txt", "r")
data = File.read()
File.close()
for org, new in zip(ORG, NEW):
    data = data.replace(org, new)
File = open("/home/pi/gpsMaster/WiScan.txt", "w")
File.write(data)
File.close()

(Note the way zip works: https://docs.python.org/2/library/functions.html#zip)

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly and was exactly what I was looking for. Thanks! I was trying to use zip before I posted this but wasn't able to figure it out.
1

If I am reading your question right, you are opening the same file, making a small alteration, saving it, and then closing it again, five times. You could just open it once, make all the alterations, and then save it. For instance, like this:

filename = "/home/pi/gpsMaster/WiScan.txt"
with open(filename, 'r') as fin:
    data = fin.read()
data = data.replace("Address:", "\nAddress, ")
data = data.replace("ESSID:", "\nESSID, ")
data = data.replace("Frequency:", "\nFrequency, ")
data = data.replace("Quality", "\nQuality, ")
data = data.replace("Signal level", "\nSignal Level, ")
with open(filename, 'w') as fout:
    fout.write(data)

If you want to use lists (ORG and NEW) for your replacements, you could do this:

with open(filename, 'r') as fin:
    data = fin.read()
for o,n in zip(ORG, NEW):
    data = data.replace(o,n)
with open(filename, 'w') as fout:
    fout.write(data)

Comments

1

Given your ORG and NEW, the simplest way to do this would be something like:

# Open once for both read and write; use with statement for guaranteed close at end of block
with open("/home/pi/gpsMaster/WiScan.txt", "r+") as f:
    data = f.read()  # Slurp file
    f.seek(0)        # Seek back to beginning of file
    # Perform all replacements
    for orig, repl in zip(ORG, NEW):
        data = data.replace(orig, repl)
    f.write(data)    # Write new data over old
    f.truncate()     # If replacement shrunk file, truncate extra

Comments

1

You could just do this:

def wiScanFormat(path = "/home/pi/gpsMaster/WiScan.txt"): 

    # List of tuples with strings to find and strings to replace with
    replacestr = [
                ("Address:", "\nAddress, "),
                ("ESSID:", "\nESSID, "),
                ("Frequency:", "\nFrequency, "),
                ("Quality", "\nQuality, "),
                ("Signal level", "\nSignal Level, ")
                ]

    with open(path, "r") as file:               # Open a file
        data = file.read()

    formated = data
    for i in replacestr:                        # Loop over each element (tuple) in the list
        formated = formated.replace(i[0], i[1]) # Replace the data

    with open(path, "w") as file:
        written = file.write(formated)          # Write the data

    return written

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.