Write a server inventory file
easyReading and writing files
Problem statement
Writing a file is the mirror image of reading one:
- Open the file in write mode. If it does not exist, it is created.
- Write text into it.
- Close it, so everything is saved to disk.
Write mode replaces any old content. To add to the end instead, use append mode ("a" in Python).
Writing text does not add a line break for you. You add \n yourself where each line should end.
Common mistake: forgetting the \n, so every name lands on one line.
TEXT
Wrong:f.write("web-01")f.write("web-02")File content: web-01web-02Your task: write the servers web-01, web-02 and db-01 to inventory.txt, one per line. Then read the file back and print each line.
Expected output
TEXT
web-01web-02db-01Approach
Write each name plus a line break, then read the file back:
- Python:
open("inventory.txt", "w")opens for writing. Eachlineread back still ends with\n, soline.strip()removes it before printing. - Java:
FileWriterwrites text.readLine()already removes the line break, so no cleanup is needed. - C++:
std::ofstreamwrites.std::getlinealso removes the line break.
servers = ["web-01", "web-02", "db-01"]
with open("inventory.txt", "w") as f:
for server in servers:
f.write(server + "\n")
with open("inventory.txt") as f:
for line in f:
print(line.strip())