How To Import XLSX / CSV & TXT Files Into Python!

Python is an amazing language, but you already know that, instead of wasting your time with a background of random stuff let me just show you exactly how to import .xlsx, .csv and even .txt files into Python! I have broken down each one of these files types below so you can skip to whichever one you want to learn about.

XLSX Files

import pandas as pd

Next up all we have to do is copy this following code:

dataframe = pd.read_excel (r'DIRECTORY TO YOUR XLSX FILE')
print (dataframe)

Let me break down this code, we first initialize the variable where we store the xlsx data (dataframe is the variable). Next we use the Pandas built in function of reading in excel files (read_excel). All you have to do now is get the directory of the xlsx file and replace the text above between the quotes to your specific directory. Here is what the code will look like with the directory pasted:

import pandas as pd

dataframe = pd.read_excel(r'/Users/users/Documents/GitHub/dataapp/GoogleTrends/data/newdata.xlsx')
print (dataframe)

Now run the code, as long as the directory is right you have now imported your XLSX file into Python!

Importing CSV files

import pandas as pd

Next up, copy this code to your Python environment:

dataframe = pd.read_csv(r'DIRECTORY TO YOUR CSV FILE')
print (dataframe)

Let me break down this code, we first initialize the variable where we store the csv data (dataframe is the variable). Next we use the Pandas built in function of reading in csv files (read_csv). All you have to do now is get the directory of the csv file and replace the text above between the quotes to your specific directory. Here is what the code will look like with the directory pasted:

import pandas as pddataframe = pd.read_csv(r'/Users/users/Documents/GitHub/dataapp/GoogleTrends/data/newdata.csv')
print (dataframe)

Congrats! You have just learned how to import csv files into your Python environment!

Importing .txt files

import pandas as pddataframe = pd.read_csv('DELETE THIS TEXT AND PASTE THE TEXT FILE DIRECTORY', sep=" ", header=None)
print (dataframe)

Once copied, change the text that is in between the two quotes to your specific directory, the code should then look something like this:

import pandas as pddataframe = pd.read_csv('/Users/users/Downloads/sample-text-file.txt', sep=" ", header=None)
print (dataframe)

Once you run the code you will then be able to see that the code will import your text file into the dataframe variable! Have fun importing these data files into Python!

Data Scientist / Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store