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?

仕様

コラム名、データとなっている次のようなテキストファイルを csv に変換する方法

入力ファイル

in01.txt
市区町村コード 		131016
宛名番号 		12345678912
個人履歴番号 		1
個人履歴番号_枝番号 	1
最新フラグ 		1
改製番号 		1
世帯番号 		234567890123456

出力ファイル

out01.csv
"市区町村コード","宛名番号","個人履歴番号","個人履歴番号_枝番号","最新フラグ","改製番号","世帯番号"
"131016","12345678912","1","1","1","1","234567890123456"

プログラム

vertical_to_csv.py
#! /usr/bin/python
#
#	vertical_to_csv.py
#
#						Jul/15/2024
#
# --------------------------------------------------------------------
import	sys
import	csv
import	pandas as pd
#
# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
file_text = sys.argv[1]
file_csv = sys.argv[2]
#
fp_in = open(file_text,encoding='utf-8')
lines = fp_in.readlines()
fp_in.close()

keys=[]
data=[]
for line in lines:
	cols = line[:-1].split()
	keys.append(cols[0])
	data.append([cols[1]])
#	print(cols[0])
#	print(cols[1])
#
print(len(keys))
print(len(data))
#
df = pd.DataFrame({keys[i]: data[i] for i in range(len(keys))})
print(df.shape)
df.to_csv(file_csv,index=False,quoting=csv.QUOTE_ALL)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------

実行結果

$ ./vertical_to_csv.py in01.txt out01.csv
*** 開始 ***
7
7
(1, 7)
*** 終了 ***
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?