网络编程
位置:首页>> 网络编程>> Python编程>> Python处理CSV与List的转换方法

Python处理CSV与List的转换方法

作者:新手村的0级玩家  发布时间:2021-11-22 11:53:48 

标签:Python,CSV,List,转换

1.读取CSV文件到List


def readCSV2List(filePath):
try:
 file=open(filePath,'r',encoding="gbk")# 读取以utf-8
 context = file.read() # 读取成str
 list_result=context.split("\n")# 以回车符\n分割成单独的行
 #每一行的各个元素是以【,】分割的,因此可以
 length=len(list_result)
 for i in range(length):
  list_result[i]=list_result[i].split(",")
 return list_result
except Exception :
 print("文件读取转换失败,请检查文件路径及文件编码是否正确")
finally:
 file.close();# 操作完成一定要关闭

2.将List写入到CSV文件中


def writeList2CSV(myList,filePath):
try:
 file=open(filePath,'w')
 for items in myList:
  for item in items:
   file.write(item)
   file.write(",")
  file.write("\n")
except Exception :
 print("数据写入失败,请检查文件路径及文件编码是否正确")
finally:
 file.close();# 操作完成一定要关闭

来源:https://blog.csdn.net/u011446177/article/details/79155670

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com