A memo for reading and writing CSV files using Python. [** 3. Pandas method **](http://qiita.com/okadate/items/c36f4eb9506b358fb608#3-pandas%E3%82%92%E4%BD%BF%E3%81%86%E5% A0% B4% E5% 90% 88% E3% 81% 8A% E3% 81% 99% E3% 81% 99% E3% 82% 81) is recommended.
2014/07/28 Addition of reading (Pandas).
2014/11/28 Summarize the case of using pandas.
Use the with
statement by referring to Python documentation.
import csv
with open('some.csv', 'r') as f:
reader = csv.reader(f)
header = next(reader) #When you want to skip the header
for row in reader:
print row #Can be obtained line by line
It can be read as follows without using the with
statement.
import csv
f = open('some.csv', 'r')
reader = csv.reader(f)
header = next(reader)
for row in reader:
print row
f.close()
In this case, add a close
statement.
The with
statement is also used for writing.
import csv
with open('some.csv', 'w') as f:
writer = csv.writer(f, lineterminator='\n') #Line feed code (\n) is specified
writer.writerow(list) #For list (one-dimensional array)
writer.writerows(array2d) #You can also write a two-dimensional array
As with reading, it is OK without with
.
import csv
f = open('some.csv', 'w')
writer = csv.writer(f, lineterminator='\n')
writer.writerow(list)
writer.writerows(array2d)
f.close()
Reading with pandas is neat and often convenient.
import pandas as pd
df = pd.read_csv('some.csv')
print df # show all column
print df['A'] # show 'A' column
The read DataFrame is easy to write.
df.to_csv('some2.csv')
For how to use it, refer to ** Summary of grammar often used in pandas ** @okadate --Qiita.
Recommended Posts