国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 3.x讀寫csv文件中數(shù)字的方法示例

2020-02-16 02:10:46
字體:
供稿:網(wǎng)友

前言

本文主要給大家介紹了關(guān)于Python3.x讀寫csv文件中數(shù)字的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說了,來一起看看詳細(xì)的介紹吧。

讀寫csv文件

讀文件時(shí)先產(chǎn)生str的列表,把最后的換行符刪掉;然后一個(gè)個(gè)str轉(zhuǎn)換成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]

檢查目錄是否存在

若目標(biāo)目錄不存在,則新建一個(gè)目錄

import osjson_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)

寫文件時(shí)指定格式

參考下面的代碼,打開文件時(shí)指定utf8,轉(zhuǎn)換成json時(shí)指定ensure_ascii=False

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

避免寫成的json文件亂碼

函數(shù) enumerate(iterable, start=0)

返回一個(gè)enumerate對(duì)象。iterable必須是一個(gè)句子,迭代器或者支持迭代的對(duì)象。

enumerate示例1:

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

示例2:

>>> line = 'one'>>> for i, item in enumerate(line,4): print(i,item)4 o5 n6 e

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

class int(x=0)

class int(x, base=10)

返回一個(gè)Integer對(duì)象。對(duì)于浮點(diǎn)數(shù),會(huì)截取成整數(shù)。

>>> 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'

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)武林站長站的支持。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 扎赉特旗| 高陵县| 凤山县| 册亨县| 丰城市| 九龙县| 务川| 双柏县| 余干县| 宜阳县| 原阳县| 卓尼县| 吴旗县| 克拉玛依市| 卫辉市| 镇远县| 永康市| 晋江市| 兴安县| 调兵山市| 遂平县| 马公市| 苏尼特左旗| 应城市| 边坝县| 洪洞县| 师宗县| 普安县| 汝城县| 桐城市| 当涂县| 二连浩特市| 黄陵县| 瑞金市| 永丰县| 曲阳县| 吉木萨尔县| 云南省| 罗甸县| 云阳县| 融水|