简体   繁体   中英

Convert all DAT files in a folder to CSV files

I did a bit of Googling and came across the script below, to convert DAT files into CSV files.

import csv
import idlsave
from os import listdir
from os.path import isfile, join, splitext

dat_folder = "C:\\Users\\ryans\\OneDrive\\Desktop\\dat\\"
csv_folder = "C:\\Users\\ryans\\OneDrive\\Desktop\\csv\\"

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)

The code looks like it would work, and the logic seems sound, but when I run it I get this error message:

Exception: Invalid SIGNATURE: b'10'

All file names and extensions are in upper case. Not sure if that makes any difference. I Googled the error and didn't come up with anything useful.

Thanks Anil_M, that helped a lot! Here is my final solution.

import csv
import idlsave
from os import listdir
from os.path import isfile, join, splitext

dat_folder = "C:\\Users\\ryans\\OneDrive\\Desktop\\dat\\"
csv_folder = "C:\\Users\\ryans\\OneDrive\\Desktop\\csv\\"

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":
        with open(join(dat_folder + fullfilename)) as f:
            with open(join(csv_folder, file_name + ".CSV"), "w") as f1:
                for line in f:
                    f1.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM