0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Databricks (Spark) にてデータフレーム作成時の UnsupportedEncodingException cp932 への対応方法

Posted at

概要

Databricks (Spark) でのデータフレーム作成時に発生するUnsupportedEncodingException: cp932 エラーに対する解決策を紹介します。

FileReadException: Error while reading file file:/Workspace/Repos/share/share/cp932/sample.csv.
Caused by: UnsupportedEncodingException: cp932

image.png

このエラーは、ファイルのエンコーディングとしてcp932がサポートされていないために発生します。Python ではcp932エンコーディングが使用されるため、誤ってこのエンコーディングを指定してしまうことがあります。この問題を解決するには、encoding パラメータにcp932の代わりにms932を指定してください。これにより、エンコーディングの互換性が保たれ、エラーが解消されます。

image.png

エラーの発生方法と対応方法

ファイルを準備

Databricks Repos 上で実行することを前提としています。

import os
src_path = f"{os.getcwd()}/sample.csv"

src_data = """
col_1,col_2,col_3
a,b,c
あ,い,う
""".strip()

with open(src_path, "w", encoding='cp932') as file:
    file.write(src_data)

image.png

エラーの発生方法

schema = """
col1 string,
col2 string,
col3 string,
_corrupt_record string
"""

df = (
    spark.read.format("csv")
    .schema(schema)
    .option("header", True)
    .option("encoding", "cp932")
    .load(f"file:{src_path}")
)

df.display()
print(df.collect())
FileReadException: Error while reading file file:/Workspace/Repos/share/share/cp932/sample.csv.
Caused by: UnsupportedEncodingException: cp932

image.png

エラーの対応方法

schema = """
col1 string,
col2 string,
col3 string,
_corrupt_record string
"""

df = (
    spark.read.format("csv")
    .schema(schema)
    .option("header", True)
    .option("encoding", "ms932")
    .load(f"file:{src_path}")
)

df.display()
print(df.collect())

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?