数据类型、字符编码、文件处理

数据类型:

数字

字符串

列表

元组

字典

集合

文件处理

一.数字

整型(int)、浮点型(float)、长整型(long)、复数

#整型(int)
age = 10 #age = int(10)
#浮点型(float)
salary = 13.5 #salary = folat(13.5)
#python2当中有长整型,Python3中已经取消。
>>> x = 1+2j
>>> x.real
1.0
>>> x.imag
2.0
>>>

二.字符串

使用场景:需要描述性的地方

字符串:定义在单引号、双引号、三引号中的一串字符

#------------优先掌握的操作:------------------
#1、按索引取值(正向取+反向取) :只能取
#2、切片(顾头不顾尾,步长)
#3、长度len
#4、成员运算in和not in
#5、移除空白strip
#6、切分split
#7、循环
#-------------------需要掌握的--------------------
#1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三种玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit
#1、strip,lstrip,rstrip###strip的默认移除的是空格
name = '*****grape*********'
print(name.strip('*'))
grape

print(name.lstrip('*'))
grape*********
print(name.rstrip('*'))
*****grape

#2、lower,upper
name = '*****grape*********'
print(name.upper())
*****GRAPE*********

print(name.lower())
*****grape*********

#3、startswith,endswith
name = '*****grape.lee'
print(name.startswith('*'))
True

print(name.endswith('lee'))
True

#4、format的三种玩法
'''
#s1是使用%s进行格式化
#s2是利用format的值的位置进行格式化
#s3是利用format的关键字命名方式
#s4是根据出现的顺序进行格式化
'''
s1 = 'My name is \033[31;1m%s\033[0m:' %('grape')
print(s1)
My name is grape:
s2 = 'My name is \033[31;1m{0}\033[0m:'.format('grape')
print(s2)
My name is grape:
s3 = 'My name is \033[31;1m{name}\033[0m:'.format(name = 'grape')
print(s2)
My name is grape:
s4 = 'My name is \033[31;1m{}\033[0m,I am a \033[32;1m{}\033[0m:'.format('grape','boy')
print(s4)
My name is grape,I am a boy:

#5、split,rsplit
'''
split默认的分隔符是空格,分隔后获得的是一个用逗号','分隔的列表。
rsplit是指定从右边开始以指定数目的利用分隔符分开,并保存到列表当中。
'''
name='root:x:0:0::/root:/bin/bash'
print(name.split(':'))
['root', 'x', '0', '0', '', '/root', '/bin/bash']
print(name.rsplit(':',1))
['root:x:0:0::/root', '/bin/bash']
#6、join
tag = " "
print(tag.join(['my','name','is','grape']))
my name is grape
#7、replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','Alex',1))
#8、isdigit,常用于判断字符是否是数字
salary = '123345'
print(salary.isdigit())
True
字符串功能练习
#1、find,rfind,index,rindex,count
# name='egon say hello'
# print(name.find('o',1,3))#顾头不顾尾,找不到则返回-1,不会报错,找到了则显示索引。
# 2
# print(name.count('e',1,3))#顾头不顾尾,如果不指定范围则查找所有
# 0
# print(name.index('e',1))#顾头不顾尾,找不到会报错。找到后返回第一个找到的索引值。
# 10
#2、center,ljust,rjust,zfill
# name='egon'
# print(name.center(50,'#'))#居中,不足50的位置用#号填充。
# #######################egon#######################
# print(name.ljust(10,'#'))#左对齐,不足10位的地方用用#号填充。
# egon######
# print(name.rjust(10,'#'))#右对齐,不足10位的地方用用#号填充。
# ######egon
# print(name.zfill(10))#右对齐,不足10位的地方用用0填充。
# 000000egon
#3、expandtabs
# name='egon\thello'
# print(name.expandtabs(1))#把字符串中的tab键以1个空格的空间打印出来
# print(name.expandtabs(4))#把字符串中的tab键以4个空格的空间打印出来
# print(name.expandtabs())#默认不指定的话,是4个空格作为一个tab
# egon hello
# egon    hello
# egon    hello
#4、captalize,swapcase,title
# name='agon Ni Hao'
# print(name.capitalize())#首字母大写
# print(name.swapcase())#大小写交换
# print(name.title())#所有单词的首字母大写
# Agon ni hao
# AGON nI hAO
# Agon Ni Hao
#5、is数字系列
# num1=b'4' #bytes
# num2=u'4' #unicode,python3中无需加u就是unicode
# num3='四' #中文数字
# num4='Ⅳ' #罗马数字
#isdigt:bytes,unicode
# print(num1.isdigit()) #True
# print(num2.isdigit()) #True
# print(num3.isdigit()) #False
# print(num4.isdigit()) #False

#isdecimal:uncicode
#bytes类型无isdecimal方法
# print(num2.isdecimal()) #True
# print(num3.isdecimal()) #False
# print(num4.isdecimal()) #False

#isnumberic:unicode,中文数字,罗马数字
#bytes类型无isnumberic方法
# print(num2.isnumeric()) #True
# print(num3.isnumeric()) #True
# print(num4.isnumeric()) #True
"""
最常用的是isdigit,可以判断bytes和unicode类型,这也是最长见的数字应用场景,
如果要判断中文数字或罗马数字,则用到isnumeric
"""
#6、is其他
# name='grape123'
# print(name.isalnum())#判断字符串有字母和数字组成
# print(name.isalpha())#判断字符串只有字母组成
# print(name.isidentifier())#判断是否是标识
# print(name.islower())#判断是否全部小写
# print(name.isupper())#判断是否全部大写
# print(name.isspace())#判断是否是空格
# print(name.istitle())#判断是否是title
需要了解的字符串操作
# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1)    移除 name 变量对应的值两边的空格,并输出处理结果
print(name.strip())
# 2)    判断 name 变量对应的值是否以 "al" 开头,并输出结果print(name.startswith('al'))
# 3)    判断 name 变量对应的值是否以 "X" 结尾,并输出结果print(name.endswith('X'))
# 4)    将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
print(name.replace('l','p'))
# 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
print(name.split('l'))
# 6)    将 name 变量对应的值变大写,并输出结果print(name.upper())
# 7)    将 name 变量对应的值变小写,并输出结果print(name.lower())
# 8)    请输出 name 变量对应的值的第 2 个字符?
print(name[1])
# 9)    请输出 name 变量对应的值的前 3 个字符?
print(name[2])
# 10)    请输出 name 变量对应的值的后 2 个字符?print(name[-2:])
# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?print(name.find('e'))
# 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
print(name[:-1])
字符串练习题

三.列表

[]方括号里边可以放任意多个以逗号分隔的任意数据类型的值

#优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in
#5、追加
#6、删除
#7、循环
#pop方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.pop(2))#pop默认删除的是最后一个元素,制定索引的话,删除制定索引的元素。
print(name)

name
['hello', 'my', 'is', 'Grape.lee']
'''

'''
#insert方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.insert(1,'haha'))#在制定索引位置后边添加元素。返回值为None
print(name)
'''

'''
#append方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.append('meinv'))#在列表最后边添加一个元素,范围值为None
print(name)

None
['hello', 'my', 'name', 'is', 'Grape.lee', 'meinv']
'''

'''
#remove方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.remove('Grape.lee'))#删除列表中指定的元素,范围值为None
print(name)
'''

'''
#count方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.count('hello'))#统计列表中元素的个数。
'''

'''
#extend方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
l1 = ['haha','boy']
print(name.extend(l1))#extend用于扩着列表:把另外一个列表内所有的元素添加到自己的类表中。返回值为None
print(name)

None
['hello', 'my', 'name', 'is', 'Grape.lee', 'haha', 'boy']
'''


'''
#index方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.index('Grape.lee'))#获得指定元素的索引位置。
'''


'''
name = ['hello', 'my', 'name', 'is', 'Grape.lee']
print(name.reverse())#将列表里边的元素顺序颠倒。返回值为None
print(name)

None
['Grape.lee', 'is', 'name', 'my', 'hello']
'''

'''
#sort方法
name = ['hello', 'my', 'name', 'is', 'Grape.lee','aaabbb','123','_123']
print(name.sort())#对列表里边的元素排序,顺序为"字符串数字 < 大写字母 < 下划线 < 小写字母",返回值None
print(name)

None
['123', 'Grape.lee', '_123', 'aaabbb', 'hello', 'is', 'my', 'name']
'''

print('a' > 'A')
print('a'> '1')
列表方法练习
#1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
# data=['alex',49,[1900,3,18]]
# name = data[0]
# age = data[1]
# year = data[2][0]
# month = data[2][1]
# day = data[2][2]
# print(name,age,year,month,day)
# alex 49 1900 3 18

#2. 用列表模拟队列
'''
#apped方式模拟队列
#入栈:
l1 = []
l1.append('one')
l1.append('two')
l1.append('three')

#出栈
l1 = ['one', 'two', 'three']
print(l1.pop(0))
print(l1.pop(0))
print(l1.pop(0))
'''
'''
#insert方式模拟队列
#入栈
l1 = []
print(l1.insert(0,'one'))
print(l1.insert(1,'two'))
print(l1.insert(2,'three'))
print(l1)
#出栈

print(l1.pop(0))
print(l1.pop(0))
print(l1.pop(0))
'''

#3. 用列表模拟堆栈
'''
#入栈:
l1 = []
l1.append('one')
print(l1)
l1.append('two')
print(l1)
l1.append('three')
print(l1)
#出栈
print(l1.pop())
print(l1.pop())
print(l1.pop())
'''
#4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]

print(l.sort(key = lambda i:i['age']))
print(l)

None
[{'name': 'egon', 'age': 18}, {'name': 'oldboy', 'age': 73}, {'name': 'alex', 'age': 84}]
列表练习题

四.元组

 可以存储个任意类型元素的不可变列表,放在()里边。

#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取   
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in
#5、循环
'''
name = ('hello', 'my', 'name', 'is', 'Grape.lee')
print(name.index('name'))#获得指定元素的索引值
print(name.count('is'))#统计指定元素的个数
print(len(name))#获得元组的元素个数
print(name[1])#获得指定索引所在位置的元素的值。
print(name[1:3])
print(name[-1:])
print(name[-3:])#反向取值的时间也是取值索引的数字大小从左到右依次增大,例如:[-3:-1],[-10:-6]
print(name[-3:-1])
print('hello' in name)
'''
#简单购物车,要求如下:
实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}

shop_list = []
while True:
    for k,v in msg_dic.items():
        print(k,v)
    goods = input("\033[31;1m请输入你要买的商品名:\033[0m").strip()
    if len(goods) == 0 or goods not in msg_dic.keys():
        continue
    num = input("\033[31;1m请输入你要购买的数量:\033[0m").strip()
    if not num or not num.isdigit():continue
    shop_list.append((goods,msg_dic[goods],num))
    print(shop_list)
元组练习题

五.字典

字典是一种无序的键值对,key 必须是不可变元素,value可以是任意类型的元素。

#优先掌握的操作:
#1、按key存取值:可存可取
#2、长度len
#3、成员运算in和not in

#4、删除
#5、键keys(),值values(),键值对items()
#6、循环
info={'name':'egon','age':18,'sex':'male'}
'''
#keys方法:
print(info.keys())#dict_keys(['name', 'age', 'sex'])
'''

'''
#items方法:
print(info.items())#dict_items([('name', 'egon'), ('age', 18), ('sex', 'male')]
'''

'''
#get方法:
print(info.get('age'))#18
'''

'''
#pop方法:
print(info.pop('name'))#删除制定key的元素,并返回对应的value
# print(info)
'''

'''
#popitem方法:
print(info.popitem())#随机弹出一个键值对,并返回弹出的键值对的元组。
'''


'''
#values方法:
print(info.values())#获得所有的values

dict_values(['egon', 18, 'male'])
'''


'''
#setdefault方法:
print(info.setdefault('age',38))
print(info.setdefault('job','teacher'))#setdefault,如果setdefault制定的key已经存在则什么都不做,如果key不存在就追加到字典中。追加成功的话返回成功的值,不成功返回原来的值。
print(info)


18
teacher
{'name': 'egon', 'age': 18, 'sex': 'male', 'job': 'teacher'}
'''

'''
#update方法:
print(info.update({'age':'38'}))#利用字典更新老的字典,返回值为None
print(info)

None
{'name': 'egon', 'age': '38', 'sex': 'male'}
'''

'''
#fromkeys方法:根据序列生成对应的key,value默认用None填充,如果指定了就用指定的value。
ltmp = ['a','b','c']
print(info.fromkeys([1,2,3,4,5,6],'good'))
print(info.fromkeys([1,2,3,4,5,6]))
print(info)
print(info.fromkeys(ltmp))
print(info)
'''

'''
#len,for循环
print(len(info))
print('name' in info)
for key in info:
    print(key)

for k,v in info.items():
    print(k,v)


for k in info.keys():
    print(k)


for v in info.values():
    print(v)
'''
字典属性练习 
'''
1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

l1 = [11,22,33,44,55,66,77,88,99,90]
d1 = {'k1':[],'k2':[]}
for i in l1:
    if i > 66:
        d1['k1'].append(i)
    else:
        d1['k2'].append(i)
print(d1)
'''

'''
2 统计s='hello alex alex say hello sb sb'中每个单词的个数

结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
#方法一:
s='hello alex alex say hello sb sb'
d1 = {}
for i in s.split():
    d1.setdefault(i,s.split().count(i))
print(d1)

#方法二:
s='hello alex alex say hello sb sb'
d1 = {}
for i in s.split():
    if i in d1:
        d1[i] += 1
    else:
        d1[i] = 1
print(d1)
'''
字典练习题

六.集合

#定义集合:
            集合:可以包含多个元素,用逗号分割,
            集合的元素遵循三个原则:
             1:每个元素必须是不可变类型(可hash,可作为字典的key)
             2:没有重复的元素
             3:无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
 

#优先掌握的操作:
#1、长度len
#2、成员运算in和not in

#3、|合集
#4、&交集
#5、-差集
#6、^对称差集
#7、==
#8、父集:>,>= 
#9、子集:<,<= 
'''
一.关系运算
有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
1. 求出即报名python又报名linux课程的学员名字集合
2. 求出所有报名的学生名字集合
3. 求出只报名python课程的学员名字
4. 求出没有同时报这两门课程的学员名字集合
'''
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
print(pythons & linuxs)
print(pythons | linuxs)
print(pythons - linuxs)
print(pythons ^ linuxs)
集合练习
#!/usr/bin/env python
# -*- coding:UTF-8 -*-

'''
#作业二:请闭眼写出购物车程序
#需求:
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
'''


goods_list = [['Iphone7',5800],
                ['Coffee',30],
                ['疙瘩汤',10],
                ['Python Book',99],
                ['Bike',199],
                ['ViVo X9',2499],

                ]
do_list = ["注册","登录","购物"]
shopping_cart={}
current_userinfo=[]

db_file=r'db.txt'


while True:
    for i in enumerate(do_list):
        print(i)
    choice = int(input("请输入你想要的操作,0 or 1 or 2:").strip())
    if choice == 0:
        username = input("请输入你要注册的用户名:").strip()
        while True:
            password1 = input("请输入你的密码:").strip()
            password2 = input("请再次输入你的密码:").strip()
            if password1 == password2:
                print("恭喜你注册成功!!!")
                break
            else:
                print("你输入的两次密码不一致请重新输入:")
        recharge = int(input("请输入充值金额:").strip())
        with open('db.txt', 'a', encoding='utf-8') as f:
            f.write('%s,%s,%s\n' % (username, password2,recharge))


    elif choice == 1:
        tag = True
        count = 0
        while tag:
            if count == 3:
                print("用户名密码尝试失败次数太多,已经被锁定!")
                break
            username = input("请输入你的用户名:").strip()
            password = input("请输入密码:").strip()
            with open('db.txt','r',encoding='utf-8') as f:
                for line in f:
                    line = line.strip('\n')
                    user = line.split(',')[0]
                    pwd = line.split(',')[1]
                    recharge = line.split(',')[2]
                    if line.split(',')[0] == username and line.split(',')[1] == password:
                        print("恭喜你登录成功")
                        current_userinfo = [user,recharge]
                        tag = False
                        break
                else:
                    print("用户名密码错误")
            count += 1

    elif choice == 2:
        if len(current_userinfo) == 0:
            print("请先登录:")
        else:
            print("商品列表:")
            for index,goods in enumerate(goods_list):
                print(index,goods)
            tag = True
            while tag:
                chose_goods_order = input("请输入你要购买的商品编号:").strip()
                if chose_goods_order == 'q':
                    for k,v in shopping_cart.items():
                        print(k,v)
                    tag = False
                    break
                elif int(chose_goods_order) < 0 or int(chose_goods_order) >= len(goods_list):
                    print("输入的编号超出了范围")
                    continue
                else:
                    goods_name = goods_list[int(chose_goods_order)][0]
                    goods_price = int(goods_list[int(chose_goods_order)][1])
                    num1= int(input("请输入购买的数量:").strip())
                    if int(current_userinfo[1]) >= goods_price * num1:
                        shopping_cart[goods_name] = goods_price * num1
                        current_userinfo[1] = int(current_userinfo[1]) - goods_price * num1

                        continue
                    else:
                        print("资金不足")
                        break
        print("资金余额是%s" %current_userinfo[1])
        break
购物车小程序
#!/usr/bin/env python
# -*- coding:UTF-8 -*-


menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}
tag = True
while tag:
    for key_1 in menu:
        print(key_1)
    select1 = input("请输入你要选择的地区:").strip()
    if not select1:continue
    if select1 == 'b':
        break
    if select1 == 'q':
        tag = False
    while tag:
        for key_2 in menu[select1]:
            print(key_2)
        select2 = input("请输入你要选择的区:").strip()
        if not select2: continue
        if select2 == 'b':
            break
        if select2 == 'q':
            tag = False
        while tag:
            for key_3 in menu[select1][select2]:
                print(key_3)
            select3 = input("请输入你要选择的街道:").strip()
            if not select3:continue
            if select3 == 'b':
                break
            if select3 == 'q':
                tag = False
            while tag:
                for key_4 in menu[select1][select2][select3]:
                    print(key_4)
                select_last = input("请输入你的最后选择:").strip()
                if not select_last:continue
                if select_last == 'b':
                    break
                if select_last == 'q':
                    tag = False
三级菜单一
#!/usr/bin/env python
# -*- coding:UTF-8 -*-

'''
这个方式是按照老师的方法重新写了一遍。
'''


menu = {
    '北京':{
        '海淀':{
            '五道口':{
                'soho':{},
                '网易':{},
                'google':{}
            },
            '中关村':{
                '爱奇艺':{},
                '汽车之家':{},
                'youku':{},
            },
            '上地':{
                '百度':{},
            },
        },
        '昌平':{
            '沙河':{
                '老男孩':{},
                '北航':{},
            },
            '天通苑':{},
            '回龙观':{},
        },
        '朝阳':{},
        '东城':{},
    },
    '上海':{
        '闵行':{
            "人民广场":{
                '炸鸡店':{}
            }
        },
        '闸北':{
            '火车战':{
                '携程':{}
            }
        },
        '浦东':{},
    },
    '山东':{},
}

layers = [menu]

while True:
    if len(layers) == 0: break
    current_layer=layers[-1]#这里以取到对应层次的字典
    for key in current_layer:#到对应层的字典边取key值
        print(key)

    choice=input('>>: ').strip()

    if choice == 'b':
        layers.pop(-1)
        continue
    if choice == 'q':break

    if choice not in current_layer:continue

    layers.append(current_layer[choice])#每次选择一层就把该层的字典追加到对应的memu列表中。
三级菜单二
#!/usr/bin/env python
# -*- coding:UTF-8 -*-

'''
             #max_level=5
    *        #current_level=1,空格数=4,*号数=1
   ***       #current_level=2,空格数=3,*号数=3
  *****      #current_level=3,空格数=2,*号数=5
 *******     #current_level=4,空格数=1,*号数=7
*********    #current_level=5,空格数=0,*号数=9

#数学表达式
空格数=max_level-current_level
*号数=2*current_level-1
'''



max_level = 5
print(type(max_level))
for current_level in range(1,max_level+1):
    print((max_level - current_level) * ' ' + (2*current_level -1)*'*')
    print()
金字塔练习题
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
'''
九九阶乘打印
'''


for i in range(1,10):
    for j in range(1,i+1):
        if i <= j:
            print('%s*%s=%s' %(i,j,i*j),end=' ')
        else:
            print('%s*%s=%s' %(j,i,i*j),end=' ')
    print()
九九阶乘

 七.文件处理

1.计算机系统组成:

计算机硬件、操作系统、应用程序

2.计算机操作文件的原理:

我们使用python或者其它语言编写的程序若想把数据永久的保存下来,必须要保存在硬盘中,这就涉及到了应用程序要操作硬件,众所周知,应用程序是无法直接操作硬件的,这就用到了操作系统。操作系统把复杂的硬件操作封装成简单的接口给用户/应用程序使用。其中文件是操作系统提供给应用程序来操作硬盘的虚拟概念,用户或应用程序通过操作文件,可以将自己的数据永久的保存下来。

3.操作文件的流程:

#1.打开文件,得到文件句柄并赋值给一个变量

#2.通过文件句柄对文件进行操作

#3.关闭文件。
操作模式:
f = open('a.txt','r',encoding='utf-8')
f.read()
f.close()
以上这种模式需要手动的去关闭f文件句柄的open函数。

with open('test1.txt','r',encoding='utf-8') as f:
    pass
使用with语句可以不用关闭文件,方便保险。


'''
with open('test1.txt','r',encoding='utf-8') as f:
    print(f.read())#一次性全部读到内存中
    print(f.readlines())#列表形式打印出所有结果
    print(f.readline())#一次读取一行
    print(f.readable())#判断是否可读
'''


'''
l = ['wukong\n','bajie\n','shaseng\n']
with open('b.txt','w',encoding='utf-8') as f:
    print(f.write('hahah\nwukong\ntangseng\n'))
    print(f.writelines(l))#wirtelines是读取列表、元组等里边的每个元素循环写入文件,相当于一个for循环
'''

'''
with open('d.txt','wb') as f:
     f.write('你好'.encode('utf-8'))
'''
文件处理常用操作
#1. 打开文件的模式有(默认为文本模式):
r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
w,只写模式【不可读;不存在则创建;存在则清空内容】
a, 之追加写模式【不可读;不存在则创建;存在则只追加内容】

#2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
rb 
wb
ab
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

#3. 了解部分
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
a+, 写读【可读,可写】


x, 只写模式【不可读;不存在则创建,存在则报错】
x+ ,写读【可读,可写】
xb
文件操作模式
'''
练习,利用b模式,编写一个cp工具,要求如下:

  1. 既可以拷贝文本又可以拷贝视频,图片等文件

  2. 用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target_file

  提示:可以用import sys,然后用sys.argv获取脚本后面跟的参数
'''
import sys
if len(sys.argv) != 3:
    print("usage: cp source_file target_file")
    sys.exit()

src_file,dest_file = sys.argv[1],sys.argv[2]
with open(src_file,'rb') as f1,\
        open(dest_file,'wb') as f_new:
        for line in f1:
            f_new.write(line)

方法一:
#模拟文件修改:
#一次性的读取所有值,并修改,然后保存到新的文件。最后删除老文件,把新文件重命名为老文件的名字。
# import os
# with open('file_old','r',encoding='utf-8') as f_old,\
#     open('file_new','w',encoding='utf-8') as f_new:
#     data = f_old.read()
#     data=data.replace('wukong','meihouwang')
#     f_new.write(data)
#
# os.remove('file_old')
# os.rename('file_new','file_old')
方法二:
import os
with open('file_old','r',encoding='utf-8') as f_old,\
    open('file_new','w',encoding='utf-8') as f_new:
    for line in f_old:
        line = line.replace('wukong','meihouwang')
        f_new.write(line)
os.remove('file_old')
os.rename('file_new','file_old')
文件处理练习题
1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数,求出本次购物花费的总钱数
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
'''
# sum = 0
# with open('a.txt','r',encoding='utf-8') as f:
#     for line in f:
#         m1 = int(line.split()[1])*int(line.split()[2])
#         sum += m1
#     print(sum)
文件练习2

 

 

 

posted @ 2018-04-08 21:53  grape_lee  阅读(307)  评论(0编辑  收藏  举报