Search code examples
pythonpandasdataframefilepathfile-read

Escape characters when joining strings


Trying to read a .csv file content from folder. Example code:

Files_in_folder = os.listdir(r"\\folder1\folder2")
Filename_list = []

For filename in files_in_folder:
    If "sometext" in filename:
         Filename_list.append(filename)

Read_this_file = "\\folder1\folder2"+max(filename_list)

Data = pandas.read_csv(Read_this_file,sep=',')

Fetching the max filename works, but the Data variable fails:

FileNotFoundError: no such file or directory.

I am able to access the folder as we see in my first line of code, but when I combine two strings, putting the r in front doesn't work, any ideas?


Solution

  • You need to add \ to your path when concatenating:

    read_this_file = '\\folder1\\folder2\\' + max(filename_list)
    

    But a better way to avoid that problem is to use

    os.path.join("\\folder1\\folder2", max(filename_list))