Python 官方文档:入门教程 => 点击学习
本文来介绍用python读取csv文件。什么是csv(Comma-Separated Values),也叫逗号分割值,如果你安装了excel,默认会用excel打开csv文件。 1. 我们先制作一个csv文件,example
本文来介绍用python读取csv文件。什么是csv(Comma-Separated Values),也叫逗号分割值,如果你安装了excel,默认会用excel打开csv文件。
1. 我们先制作一个csv文件,example.csv
2. 看看如何用Python来读取这个文件
import csv
with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
print(row)
运行输出效果
['city', 'passWord', 'day']
['Beijing', 'DJOYnieT8234jlsK', '1']
['Shanghai', 'DJOYnieT8234jlsK', '2']
['Guangzhou', 'DJOYnieT8234jlsK', '3']
['Shenzhen', 'DJOYnieT8234jlsK', '1']
>>>
3. 进入到某一个单元格
import csv
with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
# print(row)
print(row[0])
print(row[0],row[1])
4. 如何单独每列输出打印
import csv
with open(r'C:\Users\Anthony\Desktop\example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
citys = []
password = []
days = []
for row in readCSV:
city = row[0]
paword = row[1]
day = row[2]
citys.append(city)
password.append(paword)
days.append(day)
print(citys)
print(password)
print(days)
上面这个r表示不需要转义,原义输出,因为上面有\,反斜杠默认是转义,所以需要添加r输出效果
>>>
================= RESTART: C:\Users\Anthony\Desktop\demo.py =================
['city', 'Beijing', 'Shanghai', 'Guangzhou', 'Shenzhen']
['password', 'DJOYnieT8234jlsK', 'DJOYnieT8234jlsK', 'DJOYnieT8234jlsK', 'DJOYnieT8234jlsK']
['day', '1', '2', '3', '1']
>>>
--结束END--
本文标题: Python 3基础教程24-读取csv
本文链接: https://lsjlt.com/news/185317.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0