Python 3.x读写csv文件中数字的方法示例

Evan
Evan
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍Python 3.x读写CSV文件中数字的方法,包括将字符串列表转换为整数、处理换行符、检查并创建目录、指定UTF-8编码写入JSON文件避免乱码,以及使用enumerate和int函数的具体示例与注意事项。

前言

本文主要介绍Python 3.x环境下读写CSV文件中数字的相关操作,供读者参考学习。

读写csv文件

读取文件时,首先获取包含字符串的列表,并移除末尾的换行符;随后将这些字符串逐一转换为整数类型。

## 读写csv文件
csv_file = 'datas.csv'
csv = open(csv_file,'w')
for i in range(1,20):
 csv.write(str(i) + ',')
 if i % 10 == 0:
  csv.write('\n')
csv.close()
result = []
with open(csv_file,'r') as f:
 for line in f:
  linelist = line.split(',')
  linelist.pop()# delete: \n
  for index, item in enumerate(linelist):
   result.append(int(item))
print('\nResult is \n' , result)

输出结果如下:

Result is
 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

检查目录是否存在

如果目标目录不存在,则创建一个新的目录。

import os
json_dir = "../dir_json/2017-04/"
if not os.path.exists(json_dir):
 print("json dir not found")
 os.makedirs(json_dir)
 print("Create dir " + json_dir)

写文件时指定格式

参考以下代码,打开文件时指定编码为utf8,在转换为JSON时指定ensure_ascii=False。

import json
json_file = open(json_dir + id + '.json', 'w', encoding='utf8')
json_file.write(json.dumps(data_dict, ensure_ascii=False))

避免生成的JSON文件出现乱码。

函数 enumerate(iterable, start=0)

返回一个enumerate对象。iterable参数必须是一个序列、迭代器或支持迭代的对象。

enumerate示例1:

>>> data = [1,2,3]
>>> for i, item in enumerate(data):
 print(i,item)
0 1
1 2
2 3

示例2:

>>> line = 'one'
>>> for i, item in enumerate(line,4):
 print(i,item)
4 o
5 n
6 e

参考文档:https://docs.python.org/3/library/functions.html?highlight=enumerate#enumerate

class int(x=0)

class int(x, base=10)

返回一个Integer对象。对于浮点数,会截取小数部分得到整数。

>>> print(int('-100'),int('0'),int('3'))
-100 0 3
>>> int(7788)
7788
>>> int(7.98)
7
>>> int('2.33')
Traceback (most recent call last):
 File "<pyshell#27>", line 1, in <module>
 int('2.33')
ValueError: invalid literal for int() with base 10: '2.33'

总结

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对本站的支持。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表