pandas read csv in Python

In Python, you can use pandas.read_csv() to read csv files. It returns a Pandas DataFrame.

You will learn how to use pandas to load csv files in several examples below. And I also have a tutorial for pandas.read_excel() if you are looking for that.

Use pandas.read_csv() with header

Import pandas module and call pandas.read_csv() with parameter filepath, sep, and header. It returns a pandas.DataFrame of the contents of the file.

1
2
3
4
5
6
import pandas as pd
pd.read_csv('/path/to/file.csv', sep = ',' , header = 0 )

# if you need to skip 2 lines, use skiprows
pd.read_csv('/path/to/file.csv', sep = ',' , skiprows = 2, header = 0 )
#
  

Import csv file with no header

With parameter header = None, read_csv() will return the DataFrame without header. In case, you need to skip the first row, use skiprows parameter.

1
2
3
4
5
6
import pandas as pd
pd.read_csv('/path/to/file.csv', sep = ',' , header = None )

# if you need to skip the first row, use skiprows
pd.read_csv('/path/to/file.csv', sep = ',' , skiprows = 1, header = None )
#
  

Open txt file with tab separated

The code example below is pretty self-explanatory.

1
2
3
4
import pandas as pd
# load csv file in relative subfolder with \t
pd.read_csv('../subfolder/file.txt', sep = '\t' )
#
  

Additional reading: Read more about pd.read_csv() in the Pandas documentation.

Now you have learn from the examples above to use pandas.read_csv(). Have a great day!