我有一个包含许多* .dat文件的文件夹(使用程序IDL创建)。我可以获取一个文件,将其转换为* .csv文件并将其保存在另一个(现有的)文件夹中:
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)
行 input_file = idlsave.read(" C:/Users/RAW/06211714.dat")显示以下输出:
可用变量:原始类[' numpy.recarray']
所以,这只能用于获取一个文件,但我正在寻找一种方法来同时获取所有* .dat文件,并将它们中的每一个转换为原始名称的* .csv文件。 我在考虑这样的事情,但它没有工作:
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)
有人可以给我一些建议吗? 感谢。
答案 0 :(得分:1)
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)