Мы можем использовать .textFile
, чтобы получить first
строку файла CSV и захватить delimiter
, присвоенный переменной.
- Используйте переменную
delimiter
для чтения csv file
Example:
#sample data
$ cat test.csv
#NAME|AGE|COUNTRY
#a|18|USA
#b|20|Germany
#c|23|USA
#read as textfile and get first row then createdataframe with stringtype
#using regexp_extract function matching only ,|; and extracting assign to delimiter
delimiter=spark.createDataFrame(sc.textFile("file_path/test.csv").take(1),StringType()).\
withColumn("chars",regexp_extract(col("value"),"(,|;|\\|)",1)).\
select("chars").\
collect()[0][0]
delimter
#u'|'
#read csv file with delimiter
spark.read.\
option("delimiter",delimiter).\
option("header",True).\
csv("file_path/test.csv").show()
#+----+---+-------+
#|NAME|AGE|COUNTRY|
#+----+---+-------+
#| a| 18| USA|
#| b| 20|Germany|
#| c| 23| USA|
#+----+---+-------+