In [1]:
import csv
In [2]:
with open('data/temp/sample_writer_row.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow([0, 1, 2])
writer.writerow(['a', 'b', 'c'])
In [3]:
with open('data/temp/sample_writer_row.csv') as f:
print(f.read())
In [4]:
l = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34]]
print(l)
In [5]:
with open('data/temp/sample_writer.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(l)
In [6]:
with open('data/temp/sample_writer.csv') as f:
print(f.read())
In [7]:
with open('data/temp/sample_writer_row.csv') as f:
print(f.read())
In [8]:
with open('data/temp/sample_writer_row.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(['X', 'Y', 'Z'])
In [9]:
with open('data/temp/sample_writer_row.csv') as f:
print(f.read())
In [10]:
with open('data/temp/sample_writer.tsv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerows(l)
In [11]:
with open('data/temp/sample_writer.tsv') as f:
print(f.read())
In [12]:
l = [[0, 1, 2], ['a,b,c', 'x', 'y']]
In [13]:
with open('data/temp/sample_writer_quote.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(l)
In [14]:
with open('data/temp/sample_writer_quote.csv') as f:
print(f.read())
In [15]:
with open('data/temp/sample_writer_quote_all.csv', 'w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerows(l)
In [16]:
with open('data/temp/sample_writer_quote_all.csv') as f:
print(f.read())
In [17]:
with open('data/temp/sample_writer_quote_nonnumeric.csv', 'w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
writer.writerows(l)
In [18]:
with open('data/temp/sample_writer_quote_nonnumeric.csv') as f:
print(f.read())
In [19]:
with open('data/temp/sample_writer_quote_none.csv', 'w') as f:
writer = csv.writer(f, quoting=csv.QUOTE_NONE, escapechar='\\')
writer.writerows(l)
In [20]:
with open('data/temp/sample_writer_quote_none.csv') as f:
print(f.read())
In [21]:
with open('data/temp/sample_writer_quote_char.csv', 'w') as f:
writer = csv.writer(f, quotechar="'")
writer.writerows(l)
In [22]:
with open('data/temp/sample_writer_quote_char.csv') as f:
print(f.read())
In [23]:
l = [[0, 1, 2], ['a\nb', 'x', 'y']]
In [24]:
with open('data/temp/sample_writer_linebreak.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(l)
In [25]:
with open('data/temp/sample_writer_linebreak.csv') as f:
print(f.read())
In [26]:
l = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34]]
print(l)
In [27]:
header = ['', 'a', 'b', 'c', 'd']
index = ['ONE', 'TWO', 'THREE']
In [28]:
with open('data/temp/sample_writer_header_index.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
for i, row in zip(index, l):
writer.writerow([i] + row)
In [29]:
with open('data/temp/sample_writer_header_index.csv') as f:
print(f.read())