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

yipeiwu_com5年前Python基础

前言

本文主要给大家介绍了关于Python3.x读写csv文件中数字的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

读写csv文件

读文件时先产生str的列表,把最后的换行符删掉;然后一个个str转换成int

## 读写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

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设计】的支持。

相关文章

Python的dict字典结构操作方法学习笔记

一.字典的基本方法 1.新建字典 1)、建立一个空的字典 >>> dict1={} >>> dict2=dict() >>>...

python合并文本文件示例

python实现两个文本合并 employee文件中记录了工号和姓名复制代码 代码如下:cat employee.txt:100 Jason Smith200 John Doe300 S...

springboot配置文件抽离 git管理统 配置中心详解

springboot配置文件抽离,便于服务器读取对应配置文件,避免项目频繁更改配置文件,影响项目的调试与发布 1.创建统一配置中心项目conifg 1)pom配置依赖 <pa...

python中字符串比较使用is、==和cmp()总结

经常写 shell 脚本知道,字符串判断可以用 =,!= 数字的判断是 -eq,-ne 等,但是 Python 确不是这样子的。 所以作为慢慢要转换到用 Python 写脚本,这些基本...

利用python在大量数据文件下删除某一行的例子

python修改大数据文件时,如果全加载到内存中,可能会导致内存溢出。因此可借用如下方法,将分件分段读取修改。 with open('file.txt', 'r') as old_f...