文章目录
1 file文件
a. open打开
Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。
注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。
open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。
open(file, mode='r')
完整语法:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参数说明:
- file: 必需,文件路径(相对或者绝对路径)。
- mode: 可选,文件打开模式
- buffering: 设置缓冲
- encoding: 一般使用utf8
- errors: 报错级别
- newline: 区分换行符
- closefd: 传入的file参数类型
- opener:
mode 参数有:
默认为文本模式,如果要以二进制模式打开,加上 b
b. file 对象
file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数:
c. csv文件和excel文件
CSV(Comma-Separated Values)即逗号分隔值,可以用Excel打开查看。由于是纯文本,任何编辑器也都可打开。与 Excel 文件不同,CSV 文件中:
- 值没有类型,所有值都是字符串
- 不能指定字体颜色等样式
- 不能指定单元格的宽高,不能合并单元格
- 没有多个工作表
- 不能嵌入图像图表
i. csv数据读取
在CSV文件中,以 , 作为分隔符,分隔两个单元格。
不是每个逗号都表示单元格之间的分界。所以即使CSV是纯文本文件,也坚持使用专门的模块进行处理。Python内置了csv模块。先看看一个简单的例子。
# -*- coding:utf-8 -*-
import csv
filename = "airports.csv"
with open(filename) as f:
reader = csv.reader(f)
print(list(reader))
部分结果:
'450', 'NA', 'US', 'US-TX', 'Franklin', 'no', '', '', '', '', '', '09TA'], ['322207', 'US-0426', 'small_airport', 'XWind Farm Airport', '33.724417', '-96.298306', '512', 'NA', 'US', 'US-TX', 'Ravenna', 'no', '09TA', '', '09TA', '', '', 'https://web.archive.org/web/20150925002817/http://www.airnav.com/airport/09TA'], ['322208', 'US-0427', 'small_airport', 'Evan Airport', '30.314672', '-90.907972', '17', 'NA', 'US', 'US-LA', 'Prairieville', 'no', '', '', '', '', '', ''], ['322211', 'US-0428', 'small_airport', 'Sanctuary Ranch Airport', '32.056457', '-96.045951', '264', 'NA', 'US', 'US-TX', 'Crossroads', 'no', '7TS4', '', '7TS4', '', '', ''], ['322212', 'US-0429', 'small_airport', 'Linn County Airport', '38.173431', '-94.690325', '860', 'NA', 'US', 'US-KS', 'Pleasanton', 'no', '', '', '1KS', '', '', ''], ['322221', 'US-0430', 'heliport', 'J&J New Brunswick Helistop', '40.501837', '-74.445735', '23', 'NA', 'US', 'US-NJ', 'New Brunswick', 'no', '06NJ', '', '06NJ', '', '', ''], ['322222', 'US-0431', 'heliport', "St. Mary's Good Samaritan Heliport", '38.297222', '-88.937778', '501', 'NA', 'US', 'US-IA', 'Mt. Vernon', 'no', '4IL6', '', '4IL6', '', '', ''], ['322226', 'US-0432', 'heliport', 'Honeywell Heliport', '40.837083', '-74.476694', '201', 'NA', 'US', 'US-NJ', 'Morris Plains', 'no', '12NJ', '',