Why won’t pd.read_csv accept a variable name within the file path in windows?

I’m trying to put a variable name into a file path to open a csv using spyder 5, python 3.7.9, in windows. It worked fine on the raspberry pi and also on Ubuntu but I can’t figure out the windows file path conventions. Code below

import pandas as pd

needle_size = '14mm_'
Pressure = '5mb'
test_var = needle_size+Pressure

prelim = pd.read_csv('C:UsersEdwardtxDownloadsTomsstuffdata_pp_kvalstest2Inner14mm'+test_var+'.csv') 

I get the error of a red circle with a white cross in the middle on the left of the screen and it says

‘EOL while scanning string literal pyflakes E’

What’s also weird to me is that normally the text that can be used as a variable turns black between the plus signs as opposed to being green when it’s a string. In the example above .csv is black and the rest is green, why?

Furthermore I’ve tried adding r before the path and ,’rb’ after, separately, but to no avail.


The in the file path is being mistaken for an escape character. Unfortunately, even raw strings cannot end in a backslash () character, as the ending quote would still be escaped. Try defining your path and filename separately, then join them with a format string.

path = r"C:UsersEdwardtxDownloadsTomsstuffdata_pp_kvalstest2Inner14mm"
filename = test_var + ".csv"
file_path = r"%s%s" % (path, filename)

prelim = pd.read_csv(file_path)

Reference: String and Bytes literals