F.1 CSV - JulTob/Python GitHub Wiki

import csv

Coma (or colon) separated Values

Types of files

w    write and overwrite if exists
x    Create, and crash if exists
r    Read
a    Open to append
import csv
file = open (“Stars.csv”,“w”)
newRecord = “Brian,73,Taurus\n”
file.write(str(newRecord))
file.close()

This will create a new file called “Stars.csv”, overwriting any previous files of the same name. It will add a new record and then close and save the changes to the file.

file = open (“Stars.csv”,“a”)
name = input(“Enter name: ”)
age = input(“Enter age: ”)
star = input(“Enter star sign: ”)
newRecord = name + “,” + age + “,” + star + “\n”
file.write(str(newRecord))
file.close()

This will open the Stars.csv file, ask the user to enter the name, age and star sign, and will append this to the end of the file.

file = open(“Stars.csv”,“r”)
for row in file:
print(row)

This will open the Stars.csv file in read mode and display the records one row at

file = open(“Stars.csv”,“r”)
reader = csv.reader(file)
rows = list(reader)
print(rows[1])

This will open the Stars.csv file and display only row 1. Remember, Python

file = open (“Stars.csv”,“r”)
search = input(“Enter the data you are searching for: ”)
reader = csv.reader(file)
for row in file:
if search in str(row):
print(row)

Asks the user to enter the data they are searching for. It will display all rows that contain that data anywhere in that row. starts counting from 0. a time.

import csv
file = list(csv.reader(open(“Stars.csv”)))
tmp = []
for row in file:
tmp.append(row)

A .csv file cannot be altered, only added to. If you need to alter the file you need to write it to a temporary list. This block of code will read the original .csv file and write it to a list called “tmp”. This can then be used and altered as a list

file = open(“NewStars.csv”,“w”)
x = 0
for row in tmp:
newRec = tmp[x][0] + ”,” + tmp[x][1] + ”,” + tmp[x][2] + ”\n”
file.write(newRec)
x = x + 1
file.close()

Writes from a list into a new .csv file called “NewStars.csv”.


This method only works for text-based files. First open the file (File -> Open) in the Input tab, then enter the following in the Source tab:

import sys
data = sys.stdin.read()
print(data)

This method only works for text-based files. First open the file (File -> Open) in the Input tab, then enter the following in the Source tab:

import sys
data = sys.stdin.read()
print(data)
# opening/creating and writing to a CSV file
import csv
with open("test.csv", mode="w", newline="") as f:
   writer = csv.writer(f, delimiter=",")
   writer.writerow( ["Name","City"] )
   writer.writerow( ["Craig Lou", "Taiwan"] )
# Reading from CSV file
import csv
with open("test.csv", mode="r") as f:
   reader = csv.reader(f, delimiter=",")
   for row in reader:
      print(row)