将txt文件批处理转换为csv文件

本文介绍了一种将TXT文件批量转换为CSV格式的方法。该转换器能够读取指定路径下的所有TXT文件,并将它们逐个转换为CSV格式,同时创建相应的子文件夹来保存这些CSV文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

convert_txt_to_csv(txt_path, csv_path):
        """Convert the txt file to csv file"""
        #list to store the filenames and the path
        data = list_files(path=txt_path)
        csv_data=[] #list to store the csv files

        os.makedirs(csv_path) if not os.path.exists(csv_path) else print('CSV folder existd')
        for month in range(12):
            if next(walk(csv_path))[1].__len__()==12:
                print('Folders exist')
                break
            print('Creating subdirectories')

            os.makedirs(os.path.join(next(walk(csv_path))[0],'0'+str(month+1) if month<9 else str(month+1)))

        for index in range(len(data)):
            '''Store csv filename to <csv_data> list'''
            csv_data.append(os.path.join(csv_path, data[index], split(csv_path)[1].replace('txt','csv')))

        for index in range(len(data)):
            ''' reading the text files, and convert it to csv'''
            try:
                print('Processing:{}'.format(data[index])
                int_csv = csv.reader(open[data[index],'r'),delimiter='\t')
                out_csv = csv.writer(open(csv_data[index], 'x'))
                out_csv.writerow(in_csv)
            except FileNotFoundError:
                print('File not Found: {}'.format(data[index]))


### MATLAB 中批量将 .mat 文件转换CSV 文件 为了实现这一目标,可以编写一个自定义的 MATLAB 函数来遍历指定目录下的所有 `.mat` 文件,并逐个读取这些文件的内容再将其写入对应的 CSV 文件中。下面是一个完整的解决方案。 #### 创建批处理脚本 `batch_mat_to_csv.m` 此脚本会自动查找给定路径下所有的 `.mat` 文件并执行转换操作: ```matlab function batch_mat_to_csv(directoryPath, outputDirectory) % 获取当前工作区内的所有.mat文件列表 matFiles = dir(fullfile(directoryPath, '*.mat')); for i = 1:length(matFiles) fullPath = fullfile(directoryPath, matFiles(i).name); try data = load(fullPath); % 加载.mat文件 structFields = fieldnames(data); for j = 1:length(structFields) fieldName = structFields{j}; csvFileName = [outputDirectory filesep strrep(matFiles(i).name, '.mat', '_' + fieldName + '.csv')]; writematrix(data.(fieldName), csvFileName); % 将变量保存到CSV disp(['Converted ' fullPath ' to ' csvFileName]); end catch ME warning('Error processing file: ', matFiles(i).name, ': ', ME.message); end end end ``` 该函数接受两个参数:一个是输入`.mat`文件所在的文件夹路径;另一个是指定用于存储新创建的CSV文件的目标位置[^1]。 通过上述方法可以在MATLAB环境下高效地完成从多个`.mat`文件CSV格式的数据迁移过程,同时考虑到可能出现的各种异常情况进行了简单的错误捕捉与提示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值