- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip_csv_data_source.py
More file actions
Latest commit
104 lines (80 loc) · 3.12 KB
/
Copy pathzip_csv_data_source.py
File metadata and controls
104 lines (80 loc) · 3.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
frompathlibimportPath
frompyspark.sql.datasourceimportDataSource, DataSourceReader, InputPartition
frompyspark.sql.typesimportStructType
classRangePartition(InputPartition):
def__init__(self, start, end):
self.start=start
self.end=end
classZipDataSourceReader(DataSourceReader):
def__init__(self, schema, options):
self.schema: StructType=schema
self.options=options
self.path=self.options.get("path", None)
self.numPartitions=int(self.options.get("numPartitions", 2))
print(options)
defpartitions(self):
return [RangePartition(0, 1000) foriinrange(self.numPartitions)]
defread(self, partition):
# Library imports must be within the method.
fromzipfileimportZipFile
print(partition)
try:
p=Path(self.path)
ifnotp.exists():
print(f"not exists {p}")
return
ifp.is_dir():
# a folder full of zips
# beaware of .glob() at extreme
forfileinPath(self.path).glob("**/*.zip"):
print(f"{file}")
withZipFile(file, "r") aszipFile:
fornameinzipFile.namelist():
withzipFile.open(name, "r") aszipfile:
forlineinzipfile:
yield [f"{file}, {name}{line.decode('utf-8')}"]
else:
# single zip file
withZipFile(file, "r") aszipFile:
fornameinzipFile.namelist():
withzipFile.open(name, "r") aszipfile:
forlineinzipfile:
print(type(line))
yield [f"{file}, {name}{line.decode('utf-8')}"]
exceptExceptionase:
print(e)
frompyspark.sql.datasourceimportDataSource, DataSourceReader
frompyspark.sql.typesimportStructType
classZipDataSource(DataSource):
"""
An example data source for batch query using the `Zipr` library.
"""
@classmethod
defname(cls):
return"Zip"
defschema(self):
return"line string"
defreader(self, schema: StructType):
returnZipDataSourceReader(schema, self.options)
frompyspark.sqlimportSparkSession
frompyspark.sql.functionsimportcol
defcreate_spark_session(app_name="PySpark CSV Zips Datasource Tester"):
"""
Creates and returns a Spark Session
"""
return (
SparkSession.builder.appName(app_name)
.master("local[*]")
.config("spark.memory.offHeap.enabled", "true")
.config("spark.memory.offHeap.size", "1g")
.getOrCreate()
)
if__name__=="__main__":
print("Hello")
spark=create_spark_session()
spark.dataSource.register(ZipDataSource)
# TODO: Fix re-create CSV data
# df = spark.read.format("Zip").load("./zips/x.zip").limit(3)
# print(df.collect())
df=spark.read.format("Zip").load("./zips")
df.write.format("text").mode("overwrite").save("./saves")