python保存dat文件,Python:如何将* .dat文件另存为* .csv文件到新文件夹

I have a folder with lots of *.dat files (which were created with the program IDL). I am able to take one single file, convert it to a *.csv file and save it in a different (already existing) folder:

import idlsave

import csv

input_file = idlsave.read("C:/Users/RAW/06211714.dat")

n = input_file["raw"]

with open("C:/Users/CSV/06211714.csv", "w", newline='') as f:

writer = csv.writer(f)

writer.writerows(n)

The line input_file = idlsave.read("C:/Users/RAW/06211714.dat") shows the following output:

Available variables: raw class ['numpy.recarray']

So, this works fine for just taking one file, but I am looking for a way to take all *.dat files at once and convert each of them to a *.csv file with their original name.

I was thinking of something like this, but it didn't work:

import glob

for filename in glob.glob("C:/Users/RAW/*.dat"):

for element in filename:

i = idlsave.read(element)

n = i["raw"]

with open("C:/Users/CSV/*.csv", "w", newline='') as f:

writer = csv.writer(f)

writer.writerows(n)

Can someone please give me some advice?

Thanks.

解决方案import csv

import idlsave

from os import listdir

from os.path import isfile, join, splitext

dat_folder = "/folder/to/dat/files/"

csv_folder = "/folder/to/save/new/csv/files/"

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":

input_file = idlsave.read(dat_folder + fullfilename)

n = input_file["raw"]

with open(join(csv_folder, file_name + ".csv"), "w", newline='') as f:

writer = csv.writer(f)

writer.writerows(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值