CSV in python · 菜鳥的SaaS之旅 - wirelessr
文章推薦指數: 80 %
要讀一個csv format的字串而不是檔案需要透過 StringIO ,也就是將string當成檔案。
在python2和python3稍微有點差別: try: # for Python 2.x from StringIO import ...
菜鳥的SaaS之旅
Introduction
Tools/Packages
Vagrant
Celery
Mock
Xshell
Docker
DeployApplicationasContainer
CommunicatingBetweenContainers
OrchestrationusingDockerCompose
cronjob
Pandas
Tech.Sharing
DesignPatterns
Singleton
ObviousAPI(OAPI)
sscanfinpython
Functionnameinpython
Reversedtable
Pythonic
Splitstringeverynthcharacter?
Findarrayinlist
CSVinpython
Problems
Node.jsBuildup
Blueprint
Component
Buildupwebsite
Sourcecodeoverview
Usermodels
Recordmodels
Unittest
Routing/Session
JavaScriptDate
Frontend
DrawChart
Asynchronous
PoweredbyGitBook
CSVinpython
CSV算是很常使用的格式,但真要用的時候還是有些卡卡的,這邊稍微紀錄一下兩個常見的重點:
Readcsvfromstring
Readcsvasdict
要讀一個csvformat的字串而不是檔案需要透過StringIO,也就是將string當成檔案。
在python2和python3稍微有點差別:
try:
#forPython2.x
fromStringIOimportStringIO
exceptImportError:
#forPython3.x
fromioimportStringIO
importcsv
scsv="""text,with,Polish,non-Latin,lettes
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""
f=StringIO(scsv)
reader=csv.reader(f,delimiter=',')
forrowinreader:
print('\t'.join(row))
另外,csv還是當作dict比較容易使用,這時候可以用DictReader:
f=StringIO(scsv)
reader=csv.DictReader(f,delimiter=',')
forrowinreader:
print(row['text'],row['with'],row['lettes'])
Reference
StringIODictReader
resultsmatching""
Noresultsmatching""
延伸文章資訊
- 1Reading CSVs With Python's "csv" Module
Now it's time to start using Python to read CSV files. Here, I've got a simple CSV file that cont...
- 2How to Use Python Csv Dictreader - Linux Hint
The DictReader () is used to read the file of the csv in the format of the dict object. Let's dis...
- 3csv — CSV File Reading and Writing — Python 3.10.7 ...
The csv module implements classes to read and write tabular data in CSV format. It allows program...
- 4Python DictReader读写csv文件_番茄大圣的博客
准备此文档的示例代码是基于python3.5写的。 使用csv库前,先导入csv库: import csv读取内容假设csv文件的内容如下图所示,DictReader会将第一行的 ...
- 5Python DictReader讀寫csv檔案- 程式人生
Python DictReader讀寫csv檔案 ... 使用csv庫前,先匯入csv庫: ... DictReader(csvfile) for row in reader: #迴圈列印資料的...