ErikP
ErikP

Reputation: 3

Read in file path then open file in pandas

I have an annoying issue that I cannot figure out. I am trying to pass a file path programmatically to a function but it tells me that my file path does not exist. When I pass the same file path to the function manually it runs without an issue. any help on this would be appreciated.

import pandas

#function1:
#reads in CSV_FilePath from pandas DataFrame
#adds file paths to filecollection list.

#for example:
filecollection = ["\\server\path\to\file.csv"]

for filename in filecollection:
     function2(filename)

#function2 (CSV_filePath):
data = pd.read_csv(CSV_FilePath)
#do some stuff to the data DataFrame
#Save the data

When I call function2("\\server\path\to\file.csv") everything runs fine.

When I call function1 which collects the file paths and then passes them to function2 I would get the following error:

FileNotFoundError: [Errno 2] File b'"\\server\path\to\file.csv"' does not exist: b'"\\server\path\to\file.csv"'

The file does as exist. I thought this maybe was an issue with the \\server prefix and tried it on a mapped drive K:\ and that didn't seem to be the issue. I have tried prefixing "r" in function2 (data = pd.read_csv('r'+CSV_FilePath)) and that didnt seem to help either.

Upvotes: 0

Views: 1190

Answers (1)

Priyanka
Priyanka

Reputation: 34

This is a bit sily example but works.

import pathlib
import os

path = "H:\\Directory of files\\"

for filename in os.listdir(path):

print(filename)

if pathlib.Path(path+filename).exists():

    print ("File exist")

    # Call function2 here with the file path and file name

else:

    print ("File does not exist")

Upvotes: 1

Related Questions