我试图使用Pyspark遍历文件夹并获取DataBricks中文件的名称和这些文件的路径。突然想到了一个想法,就是如果我们可以将文件名设置为变量,然后将路径分配给名为的相应文件。我们可以使用dbutils创建小部件并将文件名指定为参数,以使事情变得更容易。因此,在完成此过程之前,我一直在获取文件和文件名的路径。但是我无法弄清楚变量的创建以及在相应文件名变量中分配相应文件的路径这是代码:
import pandas as pd
import os
list1 =[]
list2 =[]
directory='/dbfs/FileStore/tables'
dir='/FileStore/tables'
for filename in os.listdir(directory):
if filename.endswith(".csv") or filename.endswith(".txt"):
file_path=os.path.join(dir, filename)
print(file_path)
print(filename)
list1.append(file_path)
list2.append(filename)
提前感谢
如果设置了使用文件名为变量分配路径,则可以尝试:
...
for filename in os.listdir(directory):
if filename.endswith(".csv") or filename.endswith(".txt"):
file_path=os.path.join(dir, filename)
print(file_path)
print(filename)
exec("%s = '%s'" % (filename, file_path))
注意,附加的引号会避免语法和名称错误。但是,该解决方案仍然充满问题。例如,看起来对exec
的调用将文件路径中的反斜杠作为unicode:
filename = 'file1'
filepath = '\maindir\foo'
exec("%s = '%s'" % (filename, filepath))
file1
'\\maindir\x0coo'
但是字典似乎更适合他的情况:
...
filenames_and_paths = {}
for filename in os.listdir(directory):
if filename.endswith(".csv") or filename.endswith(".txt"):
file_path=os.path.join(dir, filename)
print(file_path)
print(filename)
filenames_and_paths[filename] = file_path
不确定为什么要为名称和路径创建两个列表,但是如果需要,还可以使用字典理解:
filenames_and_paths = {name:path for name,path in zip(list1, list2)}
[我更建议使用Pyspark,因为os.listdir
不适用于外部存储桶/存储,因此请使用Hadoop FS API列出文件。
这是您可以改编的示例:
# access hadoop fs via the JVM
Path = sc._gateway.jvm.org.apache.hadoop.fs.Path
conf = sc._jsc.hadoopConfiguration()
# list directory
directory = Path("/dbfs/FileStore/tables/*.csv")
gs = directory.getFileSystem(conf).globStatus(directory)
# create tuples (filename, filepath), you can also filter specific files here...
paths = []
if gs:
paths = [(f.getPath().getName(), f.getPath().toString()) for f in gs]
for filename, file_path in paths:
# your process