Claie
Claie

Reputation: 25

How to create Python user defined function to read CSV files?

I'd like to create a function that reads each file I want to import as a CSV, and all the files I'd like to read are in the same folder on my desktop. So would this code be correct if I want the input to be the filename (since it's the only thing different each time I want to read a file as CSV)?

def readCSV(filename):
    filepath = 'C:\\Drive\\Desktop\\Folder\\ + filename'
    readFile = pd.read_csv(filepath)
    return readFile

or would it only work if the code is like this?

def readCSV(filename):
    filepath = C:\\Drive\\Desktop\\Folder\\ + filename
    readFile = pd.read_csv('filepath')
    return readFile

My main concern with the first function is that the filename is within a string (aka the filepath), so I am not sure if this would work in Python or not.

Upvotes: 0

Views: 1352

Answers (1)

on9_jai
on9_jai

Reputation: 120

File pathnames should be in proper string format, as in if you use the print() function to output the file path, it should be exactly the same as how you want the pathname to appear.

Therefore, your path should be the concatenation of 2 strings, the first one being the absolute path of your C: drive and the second being your file name.

"C:\\Drive\\Desktop\\Folder\\" + filename

OR if you want to use string formatting:

f"C:\\Drive\\Desktop\\Folder\\{filename}"

Upvotes: 1

Related Questions