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""
延伸文章資訊
- 1csv — 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...
- 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 in python · 菜鳥的SaaS之旅 - wirelessr
要讀一個csv format的字串而不是檔案需要透過 StringIO ,也就是將string當成檔案。在python2和python3稍微有點差別: try: # for Python 2.x...
- 4csv --- CSV 文件读写— Python 3.8.14 說明文件
csv 模块中的 reader 类和 writer 类可用于读写序列化的数据。也可使用 DictReader 类和 DictWriter 类以字典的形式读写数据。 也參考. 该实现在“Pytho...
- 5How to parse csv formatted files using csv.DictReader?
CSV, or "comma-separated values", is a common file format for data. The csv module helps you to ....