1

I have a little python script that I'm working on that will add the local weather conditions and some network information to my .bashrc file. Everything works as expected except for two bugs: first instead of removing the old data and appending the new it just appends the new data like this:

('echo [Local weather]:', 66.9, 'F', 'with', 'overcast clouds') ('echo [Your public IP is]:', 'x.x.x.x'('echo [Local weather]:', 66.9, 'F', 'with', 'overcast clouds') ('echo [Your public IP is]:', 'x.x.x.x')

and second I need to drop the formatting from the printed text, eg (parentheses, commas, etc..) so that the string appears as such:

echo [Local weather]: 66.9F with overcast clouds
echo [Public IP]: x.x.x.x

Here is the file operations portion of my script:

    with open('HOME/.bashrc', 'a') as f:
        w = "echo [Local weather]:", wx_t,"F", "with", wx_c
        i = "echo [Your public IP is]:", ip
        out = [str(w), str(i)]
        f.write('\n'.join(out)[0:-3])  

so I thought that f.write('\n'.join(out)[0:-3]) would remove the last 3 lines of the file but apparently it drops the last 3 characters of the string. What do I need to change to achieve that which I attempting? Should I be using f.writelines() instead of f.write()?

The expected result will eventually look like this:

Welcome to [hostname] You are logged in as user [some_user]
[Local time]: Mon Mar 20 08:28:32 CDT 2017.
[Local weather]: 66.56 F with clear sky
[Local IP]: 192.168.x.x [Public IP]: x.x.x.x

Thanks in advance and if this is a duplicate question I apologize. I felt I've done my due-diligence in searching for a solution but I have been unsuccessful.

UPDATE: So i fixed the formatting by changing

w = "echo [Local weather]:", wx_t,"F", "with", wx_c

to

w = "echo [Local weather]: " + str(wx_t) + " F, with " + wx_c

and using f.writelines() instead of f.write(). Also I removed f.close() as suggested by DeepSpace

Aaron Nelson
  • 181
  • 14

1 Answers1

0

The first bug is caused by using 'a' instead of 'w' in the first line. This cause Python to add to the file rather than overwrite the file.

The second bug is caused because you are joining all your data into a string, and getting [0:-3] of the joined string, rather than [0:-3] of the list out.

Your code, fixed, should look like this:

with open('HOME/.bashrc', 'w') as f:
        w = "echo [Local weather]:", wx_t,"F", "with", wx_c
        i = "echo [Your public IP is]:", ip
        out = [str(w), str(i)]
        f.write('\n'.join(out[0:-3]))  
Resin Drake
  • 528
  • 4
  • 9