day03_雷神_文件操作

day03

上周回顾_问题总结:

  1. 地址值:

li = []
name = ['name','price','count']
dic = {} #如果这里定义空列表,后边的dic[name[i]] = l2[i],就会把原来的值的地址替换掉;
with open("a.txt",mode="r+") as f:
for line in f:
l2 = line.strip().split()
# print(l2)
# dic = {}
for i in range(len(l2)):
dic[name[i]] = l2[i] #有则改之,无责增加,每次进来都是把原来的替换了,每次替换还是指代的原来的地址值,直接使得
# 原来append的列表的值也发生变化。
print(dic)
print(li)
li.append(dic)
print(li)
#运行结果
{'name': 'apple', 'price': '10', 'count': '3'}
[]
[{'name': 'apple', 'price': '10', 'count': '3'}]
{'name': 'tesla', 'price': '100000', 'count': '1'}
[{'name': 'tesla', 'price': '100000', 'count': '1'}]
[{'name': 'tesla', 'price': '100000', 'count': '1'}, {'name': 'tesla', 'price': '100000', 'count': '1'}] #之前的apple已经消失。
{'name': 'mac', 'price': '3000', 'count': '2'}
[{'name': 'mac', 'price': '3000', 'count': '2'}, {'name': 'mac', 'price': '3000', 'count': '2'}]
[{'name': 'mac', 'price': '3000', 'count': '2'}, {'name': 'mac', 'price': '3000', 'count': '2'}, {'name': 'mac', 'price': '3000', 'count': '2'}]
{'name': 'lenovo', 'price': '30000', 'count': '3'}
[{'name': 'lenovo', 'price': '30000', 'count': '3'}, {'name': 'lenovo', 'price': '30000', 'count': '3'}, {'name': 'lenovo', 'price': '30000', 'count': '3'}]
[{'name': 'lenovo', 'price': '30000', 'count': '3'}, {'name': 'lenovo', 'price': '30000', 'count': '3'}, {'name': 'lenovo', 'price': '30000', 'count': '3'}, {'name': 'lenovo', 'price': '30000', 'count': '3'}]
{'name': 'chicken', 'price': '10', 'count': '3'}
[{'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}]
[{'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}, {'name': 'chicken', 'price': '10', 'count': '3'}]

本周内容

1. is、==、id

a = "alex"
b = "alex"
>>> print(a==b) # ==是数值相等比较
True
>>> print(a is b) #is是内存地址比较
True
>>> a = "%a"
>>> b = "%a"
>>> print(a == b)
True
>>> print(a is b) #
False
>>> print(id(a),id(b)) # id 测试的是内存地址
2415540340416 2415540340304
>>> print(a,b,id(a),id(b))
%a %a 2415540340416 2415540340304

小数据池 str int

小数据池存在的意义就是节省内存。

int:-5 -- 256

str:

1,不能含有特殊字符。

2,单个元素*int不能超过21.

2. 编码二

编码类型

ascii 数字,字母 特殊字符。
字节:8位表示一个字节。
字符:是你看到的内容的最小组成单位。
abc : a 一个字符。
中国:中 一个字符。

a : 0000 1011

unicode: 万国码
起初: a : 0000 1011 0000 1011
中: 0000 1011 0000 1111
升级: a : 0000 1011 0000 1011 0000 1011 0000 1011
中: 0000 1011 0000 1111 0000 1011 0000 1011

utf-8:最少用8位表示一个字符。
a: 0000 1011
欧洲: 0000 1011 0000 1011
亚洲中:0000 1011 0000 1011 0000 1011

gbk:国标
a: 0000 1011
中:0000 1011 0000 1011 两个字节。

编码进阶

1,不同编码之间的二进制是不能互相识别的。
2,对于文件的存储,及传输 不能是unicode的编码。
python3x
int
bool
bytes:内部编码方式:(非unicode,utf-8,gbk.gb2312...)
str : 内部编码方式unicode
list
dict
tuple

bytes:内部编码方式:(非unicode,utf-8,gbk.gb2312...)
str : 内部编码方式unicode
字母:
str:表现形式:s1 = 'alex'
内部编码:unicode

bytes:表现形式:s2 = b'alex'
内部编码:非unicode

中文:
str:表现形式:s1 = '中国'
内部编码:unicode

bytes:表现形式:b1 = b'\xe4\xb8\xad\xe5\x9b\xbd'
内部编码:非unicode

示例:

s1 = 'alex'
b1 = s1.encode('utf-8') # s1是字符串,是unicode编码,使用encode,改成utf-的编码,字符类型是bytes类型,用字节表示。
print(b1,type(b1))

结果:b'alex' <class 'bytes'>

s1 = 'alex'
# str ---> bytes encode 编码
b1 = s1.encode('utf-8')
print(b1)
#bytes---> str decode 解码
s2 = b1.decode('utf-8')
print(s2)

用什么编码,就要用什么区解码

3. 集合

集合概念

1,集合 要求它里面的元素,可哈希的,不可变,元素不重复,无序。
集合本身是不可哈希的。
set1 = {}
1,关系测试。
2,去重。

集合实例

列表的去重

set1 = {1,1,2,2,3,4,4,5}
print(set1)
l1 = [1, 1, 2, 2, 3, 4, 4, 5]
print(l1)
print(list(set(l1)))

结果:

{1, 2, 3, 4, 5}
[1, 1, 2, 2, 3, 4, 4, 5]
[1, 2, 3, 4, 5]

set1.clear() #清空

print(set1) # set()表示一个空集合

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

交集 & intersection

print(set1 & set2)

print(set1.intersection(set2))

并集 | union

print(set1 | set2)

print(set1.union(set2))

差集 - difference

print(set1 - set2)

print(set1.difference(set2))

print(set2 - set1)

反交集 ^ symmetric_difference

print(set1 ^ set2)

print(set1.symmetric_difference(set2))

子集

set1 =

set2 =

print(set1 < set2)

print(set1.issubset(set2))

超集

set1 =

set2 =

print(set2 > set1)

print(set2.issuperset(set1))

set1 =

print(frozenset(set1))

4.深浅copy

三种方式

三种
1. = 都共用地址值
2.浅copy 第一层独立,后边的地址值一样
3.深copy 无论多少层,地址都是独立的

a = [1,2,[1,2,3]]
b = a
print(a[2][1],b[2][1],id(a[2][1]),id(b[2][1]))

浅copy
a = [1,2,[1,2,3]]
b = a.copy()
print(a[2][1],b[2][1],id(a[1]),id(b[1])) 第二层一样了id地址值已经

切片是浅copy
s1 = [1, 2, 3, [11, 22]]
s2 = s1[:]
print(s1, s2,id(s1),id(s2)) #这是第一层独立的地址值

s1[-1].append(666)
print(s1, s2,id(s1[-1]),id(s2[-1])) 两个都加上了666,因为在第二层地址是一样的。

s1.append(666)
print(s1, s2,id(s1),id(s2)) 只有s1加上了666,因为第一层地址是独立的。

深copy

import copy
s1 = [1, 2, 3,[11,22]]
s2 = copy.deepcopy(s1)
s1.append(666)
print(s1, s2)

s1 = [1, 2, 3,[11,22]]
s2 = copy.deepcopy(s1)
s1[-1].append(666)
print(s1, s2)
# 深copy 无论多少层,都是互相独立的。

5.文件操作

文件基础

护士主妇空姐嫂子联系方式.txt
文件路径path:d:.... # 可以加r,解决路径特殊字符转义的问题
编码方式encoding:gbk,utf-8.... #文件用什么编码写的,就要用什么编码打开
操作方式mode:读,写,读写,写读,追加,改......

f1 文件句柄,f,file,file_hander,f_h....
open()调用的内置函数,内置函数调用的系统内部的open,windows默认gbk编码,linux默认utf-8编码;
一切对文件进行的操作都是基于文件句柄f1.

实例1:

with open(r"歌单1",encoding="utf-8") as f1:
print(f1.read())
windows下创建的文件默认编码是gbk,但是pycharm创建的是utf-8,英文没有区别,都能使用,中文就不可以

print(f1.read(9))
print(f1.readline())
print(f1.readlines()) ['fdsafds\n', '中国\n', '你妹妹'] 生成一个列表格式,需要用strip去除换行符

with open(r"歌单1",encoding="utf-8",mode="r+") as f1:
for line in f1:
print(line)
print(f1.readlines())
f1.write("lalala")
print(f1.read()) read从光标位置开始读取,先write后,光标位置在写入的值后边,读取不到写入的东西了就

with open(r"2.jpg",mode='rb') as f1, open("new.jpg", mode='wb') as f2: #没有编码规则,直接就是以字节的形式读取,写入,编码是字符的编码规则
content = f1.read()
f2.write(content)

file = open(r'C:\Users\Administrator\Desktop\1.jpg',mode='rb') # 带b的bytes类型,编码是非unicode,自己做了优化,自动判断是utf-8或者是gbk等。
content = file.read()
print(content)

f = open('image1.jpg',mode='wb')
f.write(content)
file.close()
f.close()

with open('歌单1',encoding='utf-8',mode='a+') as f1:
# f1.write("追加")
# f1.seek(0)
# print(f1.read())
# print(f1.tell())
# f1.seek(1)
# print(f1.tell())
print(f1.readable())

修改歌单1
以读的模式打开源文件
以写的模式打开新文件
import os
with open('歌单1',encoding='utf-8') as f1,
open('新歌单',encoding='utf-8',mode='a+') as f2:
content = f1.read()
f2.write(content)
f2.write("""爱情伤了多少人的心 # 可以加\n实现换行
听心
微风细雨
""")
os.remove('歌单1')
os.rename('新歌单','歌单1')

import os
with open('歌单1',encoding='utf-8') as f1,
open('新歌单',encoding='utf-8',mode='a+') as f2:
for line in f1:
f2.write(line)
f2.write("""爱情伤了多少人的心 # 可以加\n实现换行
听心
微风细雨
""")
os.remove('歌单1')
os.rename('新歌单','歌单1')

实例2:

!/usr/bin/env python

-- coding:utf-8 --

f1 = open(r'd:/嫂子护士联系方式.txt', encoding='gbk', mode='r')

print(f1.read())

f1.close()

f1 = open('log1', encoding='gbk', mode='r')

print(f1.read())

f1.close()

"""
f1 文件句柄,f,file,file_hander,f_h....
open()调用的内置函数,内置函数调用的系统内部的open,
一切对文件进行的操作都是基于文件句柄f1.
执行流程:
1,打开文件,产生文件句柄。
2,对文件句柄进行操作。
3,关闭文件句柄。

"""

读 r

1 read() 全读出来

f1 = open('log1', encoding='utf-8')

content = f1.read()

print(content)

f1.close()

2 read(n) 读一部分

f1 = open('log1', encoding='utf-8')

content = f1.read(3)

print(content)

f1.close()

f1 = open('log1', mode='rb')

print(f1.read(3).decode('utf-8'))

f1.close()

r 模式 read(n) n 按照字符读取。

rb 模式 read(n) n 按照字节读取。

#3 readline() 按行读取

f1 = open('log1', encoding='utf-8')

print(f1.readline())

print(f1.readline())

print(f1.readline())

f1.close()

4 readlines()

f1 = open('log1', encoding='utf-8')

print(f1.readlines())

f1.close()

5 for 循环

f1 = open('log1', encoding='utf-8')

for line in f1: 循环是读取所有文件内容,但是只占用一个内存地址。read这种会又多少内容,占用多少内存地址。

print(line)

f1.close()

f1 = open('1.jpg', mode='rb')

print(f1.read())

f1.close()

r+ 读写 先读后写

f1 = open('log1', encoding='utf-8', mode='r+')

# print(f1.read())

# f1.write('666')

f1.write('a')

print(f1.read())

f1.close()

写:w

w 没有文件,新建文件写入内容

有原文件,先清空内容,在写入新内容。

f1 = open('log2', encoding='utf-8', mode='w')

f1.write('桃白白fdksagdfsa')

f1.close()

图片的读取及写入

f1 = open('1.jpg', mode='rb')

content = f1.read()

f2 = open('2.jpg', mode='wb')

f2.write(content)

f1.close()

f2.close()

w+ 先写后读

f1 = open('log2', encoding='utf-8', mode='w+')

f1.write('两款发动机了')

f1.seek(0)

print(f1.read())

f1.close()

追加 a

a 没有文件,新建文件写入内容

f1 = open('log3', encoding='utf-8', mode='a')

# f1.write('alex 666')

f1.write('\nalex 666')

f1.close()

a+

f1 = open('log3', encoding='utf-8', mode='a+')

f1.write('python22期')

f1.seek(0)

print(f1.read())

f1.close()

其他操作方法

readable 是否可读

writable 是否可写

f1.seek(12) # 任意调整

f1.seek(0,2) #光标调整到最后

f1.seek(0) #光标调整到开头

f1.tell() # 告诉光标的位置

f1.truncate(3) # 按照字节对原文件进行截取 必须在a 或 a+ 模式

f1 = open('log3', encoding='utf-8', mode='a+')

# f1.write('python22期')

# print(f1.read())

print(f1.readable())

print(f1.writable())

f1.close()

f1 = open('log2', encoding='utf-8')

f1.read()

print(f1.tell())

print(f1.seek(0))

print(f1.seek(0,2))

f1.seek(12) # 任意调整

f1.seek(0,2) #光标调整到最后

f1.seek(0) #光标调整到开头

print(f1.tell()) # 告诉光标的位置

f1.close()

f1 = open('log3', encoding='utf-8', mode='a+')

f1.truncate(3) # 按照字节对原文件进行截取 必须在a 或 a+ 模式

f1.close()

不用主动关闭文件句柄,

with open('log1', encoding='utf-8') as f1,\

open('log2', encoding='utf-8', mode='w') as f2:

content = f1.read()

f2.write(content)

with open('log1', encoding='utf-8') as f1:

print(f1.read())

f1.close()

pass

with open('log1', encoding='utf-8',mode='w') as f2:

f2.write('666')

文件的改

1,以读模式打开原文件。

2,以写的模式打开一个新文件。

3,将原文件读出按照要求修改将修改后的内容写入新文件。

import os
with open('file', encoding='utf-8') as f1,
open('file.bak', encoding='utf-8', mode='w') as f2:
old_content = f1.read()
new_content = old_content.replace('alex', 'SB')
f2.write(new_content)

os.remove('file')
os.rename('file.bak', 'file')
#4,删除原文件。
# 5,将新文件重命名原文件。

升级版本

import os

with open('file', encoding='utf-8') as f1,\

open('file.bak', encoding='utf-8', mode='w') as f2:

for line in f1:

new_line = line.replace('SB','alex')

f2.write(new_line)

os.remove('file')

os.rename('file.bak', 'file')

with open('log1', encoding='utf-8', mode='w') as f1:
f1.write('111')
f1.write('666')
f1.write('333')
f1.write('222')

6. 函数

return

return

1,终止函数。

2,给函数的执行者返回值。

"""
return 或者 return None
return 单个值
return 多个值 会将多个值放到一个元组中,将元组返回个函数的执行者

"""

传参

!/usr/bin/env python

-- coding:utf-8 --

s = 'lkfjsjulkjdgjdsf'

count = 0

for i in s:

count += 1

print(count)

l1 = [1, 2, 3, 4, 5, 6]

count = 0

for i in l1:

count += 1

print(count)

重复代码多。

可读性差。

s = 'lkfjsjulkjdgjdsf'

print(len(s))

s = 'lkfjsjulkjdgjdsf'

def my_len():

count = 0

for i in s:

count += 1

print(count)

'''
def 关键字 函数名():
函数体
函数执行:函数名()
函数:以功能为导向。
'''
# my_len()

s = 'lkfjsjulkjdgjdsf'

def my_len():

count = 0

for i in s:

count += 1

print(my_len())

return

1,终止函数。

2,给函数的执行者返回值。

"""
return 或者 return None
return 单个值
return 多个值 会将多个值放到一个元组中,将元组返回个函数的执行者

"""
# def func1():
# print(111)
# print(222)
# return
# print(333)
# func1()

def func1():

print(111)

print(222)

return 666

return 'alex'

return 'alex', 666, [1, 2, 3]

ret = func1()

print(ret,type(ret))

s = 'lkfjsjulkjdgjdsf'

def my_len():

count = 0

for i in s:

count += 1

return count

print(my_len())

函数的传参

def my_len(argv): # 形式参数 ,形参

count = 0

for i in argv:

count += 1

return count

s = 'lkfjsjulkjdgjdsf'

l1 = [1, 2, 3, 4, 5]

# my_len(s) # 实际参数, 实参

print(my_len(l1))

实参角度

位置参数 按照顺序一一对应

def func1(a, b, c):

print(a, b, c)

func1(1, 2, 'alex')

def max(a, b): return a if a > b else b

ret = 1 if 2 > 1 else 6

print(ret)

print(max(10, 2))

关键字传参 一一对应。

def func2(a, b):

print(a, b)

func2(b=2, a=3)

混合参数。(位置参数,关键字参数) 关键字参数必须在位置参数后面。

def func3(a, b, c, d):

print(a, b, c, d)

func3(1,2,d=3,c=5)

形参角度

位置参数。按顺序一一对应。

def func1(a, b, c):

print(a, b, c)

func1(1, 2, 'alex')

默认参数。 默认参数在位置参数的后面。

def func1():

print(a, b, c)

func1(1, 2, 'alex')

def login(name,sex='男'):

with open('register', encoding='utf-8', mode='a') as f1:

f1.write('{},{}\n'.format(name,sex))

while True:

name = input('请输入姓名:').strip()

if '1' in name:

login(name)

else:

sex = input('请输入性别:').strip()

login(name,sex)

动态参数。 *args, **kwargs 万能参数。

args:所有的位置参数,放在一个元组中。

kwargs:所有的关键字参数,放在一个字典中。

def func3(args, **kwargs): #函数的定义的时候 * 代表聚合。
print(args)
print(kwargs)
# func3(1, 2, 3, 'alex', c=6, name='wusir', age='21')
# func3(
[1, 2, 3],*(22, 33)) #函数的执行的时候 * 代表打散。
func3({'name':"alex","price":"18"},) #函数的执行的时候 * 代表打散。
结果:
()
{'name': 'alex', 'price': '18', 'age': 23}
# func3(1, 2, 3, 22, 33) #函数的执行的时候 * 代表打散。

形参的顺序 位置参数 *args, 默认参数,**kwargs

def func5(a,b,*args,sex='男',**kwargs):

print(a,b,)

print(args)

print(sex)

print(kwargs)

posted @ 2018-07-05 15:55  binglei  阅读(129)  评论(0)    收藏  举报