这里有新鲜出炉的Python多线程编程,程序狗速度看过来!
Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。
在我们日常开发中经常需要对csv文件进行读写,下面这篇文章主要给大家介绍了关于Python 3.x读写csv文件中数字的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编来一起学习学习吧。
前言
本文主要给大家介绍了关于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#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'
总结
来源: http://www.phperz.com/article/17/0911/345565.html