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)
将第二列的内容保存到 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]
这里遇到了几个问题:
代码如下:
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()
注意的问题:
把上面的内容全部放在一个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,可能有些表述不清楚