Reading file in Python using csv with examples

In this post, I will use the 'with ~ as' function for convenience.

If you use 'fileopen' function, you have to close the file, but 'with as' function doesn't need to do.

Read file:

if file 'abc.txt' content like this

-----------------------------------------------------

1,2,3,4,5

-----------------------------------------------------

The python code for reading file 'abc.txt' would be as below.

-----------------------------------------------------
import csv

with open('abc.txt', 'r') as readfile:

     csvreader = csv.reader(readfile, delimiter =  ',')

     for row in csvreader:
          for i in range(len(row)):
               print row[i]

-----------------------------------------------------

Finally, output is like this

-----------------------------------------------------
1
2
3
4
5
-----------------------------------------------------

Thanks

Have Fun!

댓글

이 블로그의 인기 게시물

미국 포닥, 한국으로 돌아가는 이유? (Why do postdoc go back to Korea?)

미국 포닥 - 비지팅 포닥 VS 풀펀딩 포닥 (Visiting Scholar VS Postdoctoral Fellow)

미국 포닥 월급 생활비, 일리노이 텍사스 포닥 (Illinois, Texas Postdoc Living Cost)