python对csv文件进行批量处理,修改csv某一列的数据并存储到新的csv文件中
导论
- 本文中采用os库对文件进行批量导入, 采用csv库进行操作,主要是csv.read()和csv.write()
- 本文解决了在新的csv文件中有空格的问题
- 本文处理的是文本文档,采用‘wt’,‘rt’,不能使用‘wb’和‘rb’的二进制读取方式
导入库
import csv import os
创建文件夹
source_path = './excel_data/'
save_path = './csv_data/'
if not os.path.exists(save_path):
    os.mkdir(save_path)
遍历文件夹中的csv文件
CsvFile = os.listdir(source_path)
先进行基于原文件列的内容的修改,再保存在新的csv中
将第二列的内容保存到 hist_column中,第一列的话采用row[0]
    with open(source_path+CsvFile[leng],'rt',encoding='utf-8') as histfile:
        hist_reader = csv.reader(histfile)
        hist_column =[row[1] for row in hist_reader]
对第一列的内容进行处理
(本文中的例子是对数据进行处理,通过仿真后的数据会带有单位(皮秒psec或者飞秒fsec),要把单位去掉,统一为皮秒,如果是飞秒的话要乘以0.001)
将修改后的数据重新赋值给column, 这里重新赋值后不能将csv中的数据最终修改掉,尝试了很多种方法都不行,如果大家有更好的方法可以分享出来,我的代码如下:
    with open(source_path+CsvFile[leng],'rt',encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        column =[row[0] for row in reader]
        # hist_number = [row[1] for row in reader]
        # print(len(hist_number))
        for i in range(len(column)):
            if('psec' in column[i]):
                column[i] = column[i].replace('psec', '')
            elif ('fsec' in column[i]):
                column[i] = column[i].replace('fsec', '')
                column[i] = float(column[i])*0.001
                column[i] = str(column[i])
            elif('sec' in column[i] and 'E' in column[i]):
                column[i] = str(0)
            else:
                column[i] = column[i]
这里遇到了几个问题:
- 同时在一个open块内读取两列数据时,第二列数据会为空 (这个问题没有解决,也没有想清楚,因此写了两个open)
- 该方法获得的列中的内容为str,需要注意
写入新的csv中
代码如下:
    with open(save_path+CsvFile[leng],'wt',encoding='utf-8',newline='') as newfile:
        writer = csv.writer(newfile)
        for col,hist in zip(column, hist_column):
            writer.writerow([col, hist])
        newfile.close()
注意的问题:
采用的写入函数为writer.writerow()括号中的数据要通过[]括起来成为一个完整的行数据
两行的数据同时进行循环迭代,采用zip()函数
最后将文件关掉 newfile.close()
如果先写写入函数,再写读出函数又一定的问题
为了防止数据出现空格的问题,可以在open中加入newline=’ ’
循环迭代,实现批量操作
把上面的内容全部放在一个for循环中,
直接放具体的代码:
import csv
import os
source_path = './excel_data/'
save_path = './csv_data/'
CsvFile = os.listdir(source_path)
if not os.path.exists(save_path):
    os.mkdir(save_path)
for leng in range(len(CsvFile)):
    with open(source_path+CsvFile[leng],'rt',encoding='utf-8') as histfile:
        hist_reader = csv.reader(histfile)
        hist_column =[row[1] for row in hist_reader]
        # print(hist_column)
    with open(source_path+CsvFile[leng],'rt',encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        column =[row[0] for row in reader]
        # hist_number = [row[1] for row in reader]
        # print(len(hist_number))
        for i in range(len(column)):
            if('psec' in column[i]):
                column[i] = column[i].replace('psec', '')
            elif ('fsec' in column[i]):
                column[i] = column[i].replace('fsec', '')
                column[i] = float(column[i])*0.001
                column[i] = str(column[i])
            elif('sec' in column[i] and 'E' in column[i]):
                column[i] = str(0)
            else:
                column[i] = column[i]
            # print(column[i])
    with open(save_path+CsvFile[leng],'wt',encoding='utf-8',newline='') as newfile:
        writer = csv.writer(newfile)
        for col,hist in zip(column, hist_column):
            writer.writerow([col, hist])
        newfile.close()
    print(str(leng)+': Finished')
每一个具体的csv的名字由两部分组成: 文件夹名字+csv名字
结语
如果大家还有更好的方法的话,可以分享出来。
如果该文章有不对的地方,请指正出来,没有系统的学习过python,可能有些表述不清楚
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号