Programming from zero

Write a server inventory file

easyReading and writing files

Problem statement

Write each server from servers = ["web-01", "web-02", "db-01"] to a file called inventory.txt, one name per line. Then read the file back and print its lines numbered from 1, like 1. web-01, followed by Wrote 3 servers to inventory.txt.

Examples

Example 1

Input: servers = ["web-01", "web-02", "db-01"]

Output: 1. web-01 2. web-02 3. db-01 Wrote 3 servers to inventory.txt

Hints

Approach

Optimal

Opening a file with mode "w" creates it, or empties it if it already exists, and lets you write text. f.write() writes exactly what you give it, so each name needs "\n" at the end to go on its own line. To read it back, open the file again without a mode (reading is the default). enumerate(f, start=1) pairs each line with a counter starting at 1, and .strip() removes the trailing newline so the output does not have blank lines in between. Reading back what you wrote is a quick way to check your output file looks right.

Python
servers = ["web-01", "web-02", "db-01"]
filename = "inventory.txt"
with open(filename, "w", encoding="utf-8") as f:
for server in servers:
f.write(server + "\n")
with open(filename, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(f"{number}. {line.strip()}")
print(f"Wrote {len(servers)} servers to {filename}")

Follow-up questions

  • Write the file in the format of an Ansible inventory, with a [web] group header above the web servers.

Frequently asked questions

Mode "w" replaces the whole file each time. Use mode "a" (append) if you want to add to the end of an existing file instead, which is how log files are usually written.