python實現csv格式檔案轉為asc格式檔案的方法
阿新 • • 發佈:2022-05-26
''' Created on 2017-3-21 @author: soundslow ''' #coding=utf-8 #python預設使用ASKII碼儲存檔案,所以在檔案開頭需要宣告儲存編碼的格式(例:#coding=utf-8) import sys from sys import argv import csv argc = '1.asc' script ,filename = argc,argv fw = open(argc, 'w') # string為:從ncols到NODATA_value這幾行是一樣的,因為資料來源是一致的 string = ("ncols 4800\nnrows 1550\nxllcorner 284687.500000\nyllcorner 2412912.500000\ncellsize 25.000000\nNODATA_value -9999.000000\n") fw.write(string) fr = open(argc, 'r') with open('result_50_1.csv') as f: reader = csv.reader(f) ''' 第一個for迴圈是為了提取出一箇中間介質row_num作為行數的表示, 由於從表格中提取的資料(行號)並不是數字型別, 不能直接使用(1 == f_rows[2]進行判斷,所以直接使用自身的型別。) (補充:應該是字串型別) ''' for i,f_rows_temp in enumerate(reader):if(i == 0): continue row_num = f_rows_temp[2] print(row_num) break #遍歷寫入資料,遍歷行數(即csv檔案第三列f_rows[2]) for i,f_rows in enumerate(reader): if(i == 0): continue if(f_rows[2] != row_num): # 判斷是否換行 fw.write('\n') row_num = f_rows[2] fw.write(f_rows[1]) fw.write(' ') sys.stdout.flush() #強制IO重新整理,寫入檔案資料 print(f_rows[1]) #兩個列印是為了便於觀察資料執行情況 print(f_rows) fw.close() fr.close()