Python处理CSV与List的转换方法

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

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

标签:Python,CSV,List,转换
0
投稿

猜你喜欢

  • 网站设计做好超级链接的重要性

    2007-09-14 11:19:00
  • python实现套接字创建

    2021-09-09 05:12:04
  • 高效地获取XMLhttp对象

    2010-01-19 13:49:00
  • python单线程文件传输的实例(C/S)

    2023-04-07 22:45:48
  • 带你轻松了解 SQL Server数据库的组成

    2009-02-05 15:53:00
  • phpMyAdmin安装配置方法

    2009-09-09 20:15:00
  • sql 存储过程分页代码 支持亿万庞大数据量

    2011-09-30 11:16:46
  • vuejs实现下拉框菜单选择

    2023-09-23 08:49:54
  • JavaScript奇怪的比较——隐式类型转换

    2009-02-15 13:06:00
  • 现代Python编程的四个关键点你知道几个

    2023-11-22 02:17:42
  • Python通过TensorFLow进行线性模型训练原理与实现方法详解

    2022-11-10 16:17:27
  • CSS执行顺序与优先权的问题

    2010-08-23 16:21:00
  • python爬取淘宝商品详情页数据

    2021-05-28 14:38:08
  • 两个命令把 Vim 打造成 Python IDE的方法

    2022-01-20 09:31:31
  • Python3.9.1中使用match方法详解

    2023-09-14 09:51:21
  • 使用Alt提升可访问性

    2009-04-04 19:22:00
  • python打开windows应用程序的实例

    2021-08-22 09:49:40
  • 8行代码实现Python文件去重

    2023-11-20 14:47:35
  • python生成以及打开json、csv和txt文件的实例

    2023-08-05 10:44:49
  • Python数据分析之 Matplotlib 3D图详情

    2021-03-05 21:20:33
  • asp之家 网络编程 m.aspxhome.com