Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

Python: How to save *.dat-files as *.csv-files to new folder

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...