读入文件路径,然后在熊猫中打开文件

时间:2020-01-24 16:43:46

标签: python python-3.x pandas

我有一个烦人的问题,无法解决。我试图以编程方式将文件路径传递给函数,但是它告诉我我的文件路径不存在。当我手动将相同的文件路径传递给函数时,它可以正常运行。任何帮助,将不胜感激。

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

当我致电function2("\\server\path\to\file.csv")时,一切运行正常。

调用function1会收集文件路径,然后将其传递给function2时,会出现以下错误:

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

该文件确实存在。我以为这可能是前缀\\server的问题,并在映射的驱动器K:\上进行了尝试,但这似乎不是问题。我曾尝试在function2 (data = pd.read_csv('r'+CSV_FilePath))中添加“ r”前缀,但这似乎也没有帮助。

1 个答案:

答案 0 :(得分:1)

这是一个有点愚蠢的例子,但是有效。

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")