Saving outputs in a single file without overwriting the previous output

Below is a piece of a long code. The last step should save the output of all devices in a single file. It should add up, not overwrite.
Now I’m getting only the output of the last device.

from netmiko import Netmiko
with open('addresses.txt') as f1:
    file1 =f1.read().splitlines()    
with open('commands.txt') as f2:
    file2 =f2.read().splitlines()

for ip in file1:
    device = {'device_type':'cisco_ios',
       'ip':ip,
       'username':'user1',
       'password':'secret1'
    }
    ssh = Netmiko(**device)
    file3 = open( '_show.txt', 'w')
    for cmd in file2:
        output = ssh.send_command(cmd)
        file3.write(output + '\n')
    file3.close()

Try changing the mode to a, which will append the data: mode ‘w’ will create a new file…

file3 = open( '_show.txt', mode='a')
1 Like

waw… awesome… it works properly now…
I though mode w is only for writing permissions. But it seems doing more than that (creating a new file every time)
So, mode a gives write permissions to the same file. Great!

No worries.

There are six access modes (that I know of):

  1. 'r' Read only: the default
  2. 'w' Write: Create a new file or overwrite the contents of an existing file.
  3. 'a' Append: Write data to the end of an existing file.
  4. 'r+' Both read and write to an existing file. The file pointer will be at the beginning of the file.
  5. 'w+' Both read and write to a new file or overwrite the contents of an existing file.
  6. 'a+' Both read and write to an existing file or create a new file. The file pointer will be at the end of the file.
2 Likes

Use python’s built-in documentation tools, see that there are text and binary modes, too.

$ python -m pydoc open
...
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================

    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
...
2 Likes

Corresponding Stack Overflow canonical:

1 Like

A good idea