6.4.2 – Write and append CSV text files
Create complete CSV reports, append records without losing existing data, and choose file modes from the required repeat-run behavior. Build and inspect real output files with explicit separators and newlines.
Writing a new CSV file
Mode "w" opens a file for writing. It creates the file if needed, but if the file already exists, its previous contents are erased. Choose it when the requirement is to create or replace the complete CSV content.
This program writes a header and two records to results.csv:
results_file = open("results.csv", "w")
results_file.write("name,score\n")
results_file.write("{},{}\n".format("Amir", 17))
results_file.write("{},{}\n".format("Bela", 20))
results_file.close()
Each call to write() receives one string. The comma inside the string separates the fields; \n ends the record. write() does not start a new line automatically. The .format(...) call forms a string, so the integer scores can be placed in the text record without using an f-string.
The supplied predicted content of results.csv after the program is:
name,score
Amir,17
Bela,20
Closing the file releases the file resource and completes any buffered write in the explicit-open style used by Pearson's PLS.
Appending and writing lists
Mode "a" opens a file for appending. Existing contents are preserved, and new text is written at the end. This differs from "w", which replaces the existing contents.
Suppose results.csv currently contains the following, and its final shown record ends with \n:
name,score
Amir,17
Bela,20
Two records can be appended together using writelines():
new_rows = ["Chen,13\n", "Dina,19\n"]
results_file = open("results.csv", "a")
results_file.writelines(new_rows)
results_file.close()
The supplied predicted final file content is:
name,score
Amir,17
Bela,20
Chen,13
Dina,19
writelines() writes the list of strings in order, but it does not add line feeds. If new_rows were ["Chen,13", "Dina,19"], the new text would be Chen,13Dina,19 on one line. This is a logic fault in the produced file even though both strings were written. Append mode can also be used with a single write() call:
results_file = open("results.csv", "a")
results_file.write("Eli,12\n")
results_file.close()
The following workspace deliberately retains its text files between runs while this activity stays mounted. Run once, inspect results.csv, then run again. Each run adds two rows: duplicates are expected because each execution is a new append request. Reset restores the original file. This local activity state is not a promise that another browser or a newly opened activity has the same file. In a school IDE files normally persist too.
Inspect two append runs
{"exercise_id": "cs-c25-append", "task_version": "1", "runtime_profile": "python-console-v1", "original_filename": "main.py", "file_mode": "persistent", "code": "rows = ["Chen,13\n", "Dina,19\n"]\noutput = open("results.csv", "a")\noutput.writelines(rows)\noutput.close()\nprint("Added:", len(rows))\n", "instructions": "Run twice and inspect the generated file after each run. Then Reset and check that only the original records remain.", "files": [{"name": "results.csv", "content": "name,score\nAmir,17\nBela,20\n"}]}
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account