0
0

パイソンでアスキーからcsv

Posted at

以下は、指定された処理をPythonで実行するコードです。空白を無視して特定の文字列を抜き出し、CSVに書き出します。

import csv

# ASCファイルのパス
asc_file_path = "path/to/your/file.asc"

# CSVファイルのパス
csv_file_path = "path/to/your/output/file.csv"

# データ抽出とCSV書き出しの関数
def process_asc_and_export_to_csv(asc_path, csv_path):
    with open(asc_path, 'r') as asc_file, open(csv_path, 'w', newline='') as csv_file:
        csv_writer = csv.writer(csv_file)
        csv_writer.writerow(["ExtractedData"])  # CSVヘッダー

        for line in asc_file:
            if line.startswith(("1.0", "2.0", "3.0")):
                # 各行から指定された位置の文字列を抜き出す(空白を無視)
                data_1 = line.split("10 12 67 01", 1)[1][:4].strip()  # 1.0 0 8  8 10 12 67 01の後の4文字
                data_2 = line.split("21", 1)[1][:7].strip()  # 2.0 0 8  8 21の後の7文字
                data_3 = line.split("22", 1)[1][:5].strip()  # 3.0 0 8  8 22の後の5文字

                # 1〜3の内容を連結してCSVに書き込む
                concatenated_data = f"{data_1}{data_2}{data_3}"
                csv_writer.writerow([concatenated_data])

# 処理を実行
process_asc_and_export_to_csv(asc_file_path, csv_file_path)

このコードでは、split関数を使用して指定された文字列を基準に行を分割し、空白を取り除くことで指定された位置の文字列を抜き出しています。これをCSVに1行ずつ書き込む形にしています。

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