前言
本文主要給大家介紹了關(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ì)武林站長站的支持。
|
新聞熱點(diǎn)
疑難解答
圖片精選