Reading and writing CSV text files in Python: open, read, write, append, close, and splitting lines on commas.
| Point | Detail |
|---|---|
| Persistent storage | |
| Between runs | |
| Common uses | |
| CSV file |
| Command | Meaning |
|---|---|
| file = open("data.txt", "r") | |
| file = open("data.txt", "w") | |
| file = open("data.txt", "a") | |
| for line in file: | |
| file.write(text) | |
| file.close() |
| Command | Meaning |
|---|---|
| line.strip() | |
| line.split(",") | |
| ",".join(fields) | |
| Types | |
| Record and field |
# each record is name,score
file = open("scores.csv", "w")
for i in range(3):
name = input("Name: ")
score = input("Score: ")
file.write(name + "," + score + "\n")
file.close()
print("Scores saved.")file = open("scores.csv", "r")
for line in file:
fields = line.strip().split(",")
name = fields[0]
score = int(fields[1])
print(name, "scored", score)
file.close()total = 0
count = 0
file = open("scores.csv", "r")
for line in file:
fields = line.strip().split(",")
total = total + int(fields[1])
count = count + 1
file.close()
if count > 0:
print(total / count)file = open("scores.csv", "a")
file.write("Sam,72\n")
file.close()A file called scores.csv already exists. What happens when a program opens it with mode "w"?
Write a Python program that reads every name from names.txt (one name per line) and prints each name with its line number (1, 2, 3...). (4 marks)
Which mode adds new data to the end of an existing file without deleting what is already there?
This program should add up the scores in data.csv (each line is name,score). It has two errors. Identify each error and write the corrected program. (4 marks)
file = open("data.csv", "r")
for line in file:
fields = line.split(",")
total = total + fields[1]
file.close()
print(total)
Each line of people.csv looks like Ava,15 followed by a newline. The line has been read into the variable line. Write Python that stores the name in a variable called name and the age, as a number, in a variable called age. (3 marks)
Why must a program close a file when it has finished with it?