1.file
1.1打开文件方式(读写两种方式)
1.1.1open()方法
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 。
1.2 file对象
file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数:
1.3 对excel和csv的操作
(1)读取csv文件:
import csv
#打开文件,用with打开可以不用去特意关闭file了,python3不支持file()打开文件,只能用open()
with open("XXX.csv","r",encoding="utf-8") as csvfile:
#读取csv文件,返回的是迭代类型
read = csv.reader(csvfile)
for i in read:
print(i)
(2)存为csv文件:
import csv
with open("XXX.csv","w",newline="") as datacsv:
#dialect为打开csv文件的方式,默认是excel,delimiter="\t"参数指写入的时候的分隔符
csvwriter = csv.writer(datacsv,dialect = ("excel"))
#csv文件插入一行数据,把下面列表中的每一项放入一个单元格(可以用循环插入多行)
csvwriter.writerow(["A","B","C","D"])
说明:csv模块还有DictReader和DictWriter可以用来读写,返回的是字典的类型,不过这两个方法我没用过,有兴趣的可以自己看看。
参考:
1.csv及excel,由于还没有熟练使用,不敢瞎写,所以在这里把引用写出来。等之后在做总结。
https://www.cnblogs.com/zhangxinqi/p/9231801.html#_label4
https://www.cnblogs.com/zle1992/p/5986317.html
2 os模块
请参考:
http://www.runoob.com/python3/python3-os-file-methods.html
3 datetime模块
请参考:
https://blog.csdn.net/qq_24753293/article/details/80954840
4 类和对象
请参考:
http://www.runoob.com/python3/python3-class.html
5 正则表达式
http://www.runoob.com/python3/python3-reg-expressions.html
6 re模块
https://www.cnblogs.com/wenwei-blog/p/7216102.html
7 http请求
https://www.cnblogs.com/zealousness/p/8748906.html