Converting multiple .dat files with binary data to .csv with same file name
我有一个文件夹,其中包含带有二进制数据的.dat文件,我想用与.dat文件相同的名称解析并写入.csv文件。我可以取一个.dat文件,并将其转换为相应的.csv文件,并将其转换为我需要的文件夹。
1 2 3 4 5 6 7 8 9 10 11 | import numpy as np import pandas as pd raw_file= '/home/targetfolder/channel1.dat' with open(raw_file,"rb") as f: raw_data = np.fromstring(f.read(), dtype=np.float32) comb_np_array = np.vstack(raw_data) big_frame = pd.DataFrame(comb_np_array) big_frame.to_csv("/home/destinationfolder/channel1.csv") f.close() |
输出文件名.csv0至47.4188671,-47.4438282,-47.44453113,-47.47382814,-47.41938715,-47.42222216,-47.4193878
下面是我执行相同操作的链接:python:如何将*.dat文件保存为*.csv文件到新文件夹
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import csv from os import listdir from os.path import isfile, join, splitext dat_folder ="/home/nri/" csv_folder ="/home/nri/tmp/" onlyfilenames = [f for f in listdir(dat_folder) if isfile(join(dat_folder,f))] for fullfilename in onlyfilenames: file_name, file_extension = splitext(fullfilename) if file_extension ==".dat": inputfile=dat_folder + fullfilename with open(inputfile,"rb") as f: inputfile = np.fromstring(f.read(), dtype=np.float32) comb_np_array = np.vstack(raw_data) n = pd.DataFrame(comb_np_array) with open(join(csv_folder, file_name +".csv"),"w", newline='') as f: writer = csv.writer(f,lineterminator=' ') for row in range(len(n)): writer.writerows(n) |
号
但上面给出了一个错误:"需要序列"。请告诉我怎样才能达到预期的效果。
您正在迭代len(n),但每次都在写n。
1 2 | for row in range(len(n)): writer.writerows(n) |
WriteRows接受序列序列,但您正在传递一个数据帧,并期望编写器对其进行迭代,但在您的情况下,数据帧不是序列(python 2?)这是你检查这个的方法。
1 2 3 | >>> import collections >>> isinstance(big_frame, collections.Sequence) False |
号
您将需要迭代数据帧并写入单元,
1 2 | for i, row in big_frame.iterrows(): writer.writerow([i, row[0]]) # 0 is the col name here |