python how to read csv file
Reading csv file in python is simple:
csv = open("/home/user/my.csv")
for line in csv:
print(line)
result:
1;2;3;4
a;b;c;d
5;6;7;8
x;y;z;0
Reading csv file without new lines
In most cases you will want to skip new lines or any other OS line separators from the csv files. In order to remove new lines use strip() method:
csv = open("/home/user/my.csv")
for line in csv:
print(line.strip())
result:
1;2;3;4
a;b;c;d
5;6;7;8
x;y;z;0
Reading csv file per element
Usually when you read csv file you will want to read the content row by row, column by column. You can do this using split method:
csv = open("/home/user/my.csv")
for line in csv:
print(line.strip().split(";"))
result:
['1', '2', '3', '4']
['a', 'b', 'c', 'd']
['5', '6', '7', '8']
['x', 'y', 'z', '0']
Reading csv file skip lines by index
You can skip lines while reading file by creating artificial index:
csv = open("/home/user/my.csv")
for i, line in enumerate(csv):
if i < 2:
continue
print(i , " ", line.strip()))
result:
2 5;6;7;8
3 x;y;z;0
Reading csv file skip lines by content
You can also skip lines by content or special character:
csv = open("/home/user/my.csv")
for i, line in enumerate(csv):
if "0" in line: # no comments
continue
print(i, " ", line.strip())
result:
0 1;2;3;4
1 a;b;c;d
2 5;6;7;8
You may see how to write csv file with python: Python how to write csv file