0
1

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 3 years have passed since last update.

DatabricksのPythonにてDBFS上に変数の値をファイルとして保存する方法

Last updated at Posted at 2021-07-14

概要

DatabricksのPythonにてDBFS上に変数の値をファイルとして保存する方法を2つ紹介します。

  1. dbutilsを利用する方法
  2. PythonのOpenを利用する方法

詳細は下記のGithub pagesのページをご確認ください。

コードを実行したい方は、下記のdbcファイルを取り込んでください。

https://github.com/manabian-/databricks_tecks_for_qiita/blob/main/tecks/put_file_to_dbfs/dbc/put_file_to_dbfs.dbc

実施手順

1. dbutilsを利用する方法

file_path = f'{file_dir}/dbutils/test.csv'
 
# データを定義
csv_data = """
string,value,date
"A","100","2021-02-01"
"B","2"00","2021-02-01"
"C","3,00","2021-02-01"
"D","400","2021-02-01"
""".strip() # strip関数により最初と最後の改行を削除

# dbfs上にファイルを保存
dbutils.fs.put(file_path, csv_data, overwrite=True)

image.png

2. PythonのOpenを利用する方法

# pythonでdbfsに書き込む場合には`/dbfs`直下に配置
file_path = f'/dbfs/{file_dir}/test.csv'
 
# データを定義
csv_data = """
string,value,date
"A","100","2021-02-01"
"B","2"00","2021-02-01"
"C","3,00","2021-02-01"
"D","400","2021-02-01"
""".strip() # strip関数により最初と最後の改行を削除

with open(file_path, 'w') as f:
    print("---書き込み開始---") 
    f.writelines(csv_data)
    print("---書き込み完了---")

image.png

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?