函数&模块&文件操作相关

一、函数

1.函数定义

函数,一个用于专门实现某个功能的代码块(可重用)。

【1】内置函数
len、bin、oct、hex 等
【2】自定义函数
def send_email():
    # 写了10行代码,实现了发送邮件。
    pass

send_email()
# 定义了一个函数,功能代码块
def send_email():
    # 写了10行代码,实现了发送邮件。
    pass

goods = [
    {
   "name": "电脑", "price": 1999},
    {
   "name": "鼠标", "price": 10},
    {
   "name": "游艇", "price": 20},
    {
   "name": "美女", "price": 998}
]
for index in range(len(goods)):
    item = goods[index]
    print(index + 1, item['name'], item['price'])

# 调用并执行函数
send_email()

while True:
    num = input("请输入要选择的商品序号(Q/q):")  # "1"
    if num.upper() == "Q":
        break
    if not num.isdecimal():
        print("用输入的格式错误")
        break
    num = int(num)
    send_email()
    if num > 4 or num < 0:
        print("范围选择错误")
        break
    target_index = num - 1
    choice_item = goods[target_index]
    print(choice_item["name"], choice_item['price'])
    send_email()

二、模块

1.模块定义

集成了很多功能的函数集合。

【1】内置模块,Python内部帮助我们提供好的。
import random

num = random.randint(0,19)
import decimal

v1 = decimal.Decimal("0.1")
v2 = decimal.Decimal("0.2")
v3 = v1 + v2
print(v3) # 0.3
【2】第三方模块,网上下载别人写好的模块(功能集合)。
【3】自定义模块

三、文件操作相关

每种格式包含很多相关操作,大家在学习的过程中只要掌握知识点的用法,参考笔记可以实现相关的练习即可,不必背会(在企业开发过程中也是边搜边实现。

1.文件操作

【1】读文件
  • 读文本文件
# 1.打开文件
#	- 路径:
#		相对路径:'info.txt'
#		绝对路径:'/Users/wupeiqi/PycharmProjects/luffyCourse/day09/info.txt'
# 	- 模式
# 		rb,表示读取文件原始的二进制(r, 读 read;b, 二进制 binary;)
# 1.打开文件
file_object = open('info.txt', mode='rb')
# 2.读取文件内容,并赋值给data
data = file_object.read()
# 3.关闭文件
file_object.close()

print(data) # b'alex-123\n\xe6\xad\xa6\xe6\xb2\x9b\xe9\xbd\x90-123'  读取的是文件的二进制
text = data.decode("utf-8")    #将文本的内容从字节转换成字符串
print(text)
# 1.打开文件
file_object = open('info.txt', mode='rt', encoding='utf-8')    # 直接读取到文件的字符串类型,无需像上方一样手动转换

# 2.读取文件内容,并赋值给data
data = file_object.read()

# 3.关闭文件
file_object.close()

print(data)
  • 读图片等非文本内容文件。
file_object = open('a1.png', mode='rb')
data = file_object.read()
file_object.close()

print(data) # \x91\xf6\xf2\x83\x8aQFfv\x8b7\xcc\xed\xc3}\x7fT\x9d{.3.\xf1{\xe8\...

== 注意事项==

  1. 路径
    - 相对路径,当前程序的目录下找文件
    - 绝对路径
# 1.打开文件
file_object = open('/Users/wupeiqi/PycharmProjects/luffyCourse/day09/info.txt', mode='rt', encoding='utf-8')
# 2.读取文件内容,并赋值给data
data = file_object.read()
# 3.关闭文件
file_object.close()

windows系统中写绝对路径容易出问题:

# file_object = open('C:\\new\\info.txt', mode='rt', encoding='utf-8')   

file_object = open(r'C:\new\info.txt', mode='rt', encoding='utf-8')    # 直接写win绝对路径会报错,可以在路径前方加上r,或者使用双斜杠 
data = file_object.read()
file_object.close()
print(data)
  1. 读文件时,文件不存在程序会报错。
Traceback (most recent call last):
  File "/Users/wupeiqi/PycharmProjects/luffyCourse/day09/2.读文件.py", line 2, in <module>
    file_object = open('infower.txt', mode='rt', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: 'infower.txt'
# 判断路径是否存在:
import os

file_path = "/Users/wupeiqi/PycharmProjects/luffyCourse/day09/info.txt"
exists = os.path.exists(file_path)    #判断路径是否存在,返回一个bool 
if exists:
    # 1.打开文件
    file_object = open('infower.txt', mode='rt', encoding='utf-8')
    # 2.读取文件内容,并赋值给data
    data = file_object.read()
    # 3.关闭文件
    file_object.close()
    print(data)
else:
    print("文件不存在")
【2】写文件
  1. 写文本文件
# 1.打开文件
# 路径:t1.txt
# 模式:wb(要求写入的内容需要是字节类型)
file_object = open("t1.txt", mode='wb')

# 2.写入内容
file_object.write(    "张三".encode("utf-8")    )

# 3.文件关闭
file_object.close()
file_object = open("t1.txt", mode='wt', encoding='utf-8')   #通过wt写入内容更方便,不用进行转换

file_object.write("张三")

file_object.close()
  1. 写图片等文件
#相当于复制图片
f1 = open('a1.png',mode='rb')
content = f1.read()
f1.close()

f2 = open('a2.png',mode='wb')
f2.write(content)
f2.close()
  1. 基础案例:
# 【1】案例1:用户注册

user = input("请输入用户名:")
pwd = input("请输入密码:")
data = "{}-{}".format(user, pwd)
file_object = open("files/info.txt", mode='wt', encoding='utf-8')   #打开某一文件时,若是文件不存在,则会创建一个
file_object.write(data)
file_object.close()


#【2】 案例2:多用户注册

# 通过w写入文件,先清空文件;再在文件中写入内容。解决方案:不要反复打开文件即可
file_object = open("files/info.txt", mode='wt', encoding='utf-8')  
while True:
    user = input("请输入用户名:")
    if user.upper() == "Q":
        break
    pwd = input("请输入密码:")
    data = "{}-{}\n".format(user, pwd)     #  \n 在程序中是换行的意思,加入后可让输如内容自动换行

    file_object.write(data)
file_object.close()

小高级案例:(超前)

# 利用Python想某个网址发送请求并获取结果(利用第三方的模块)
# 下载第三方模块requests
pip install requests   # 若使用该方法安装报错,则使用下边的代码进行安装

或者:  /Library/Frameworks/Python.framework/Versions/3.9/bin/pip3 install requests  # 此代码中的路径为py的安装目录
# 使用第三方模块
import requests

res = requests.get(url="网址")
print(res)
# 【1】 案例1:去网上下载一点文本,文本信息写入文件。
import requests

res = requests.get(
    url="https://movie.douban.com/j/search_subjects?type=movie&tag=%E7%83%AD%E9%97%A8&sort=recommend&page_limit=20&page_start=20",
    headers={
   
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
    }
)

#  res.content   网络传输的原始二进制信息(bytes)


file_object = open('files/log1.txt', mode='wb')
file_object.write(res.content)
file_object.close()



# 【2】案例2:去网上下载一张图片,图片写入本地文件。
import requests

res = requests.get(
    url="https://hbimg.huabanimg.com/c7e1461e4b15735fbe625c4dc85bd19904d96daf6de9fb-tosv1r_fw1200",
    headers={
   
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
    }
)

# 网络传输的原始二进制信息(bytes)
# res.content

file_object = open('files/张三.png', mode='wb')
file_object.write(res.content)
file_object.close()

注意事项

  • 路径
    绝对路径
    相对路径
  • 文件不存在时,w模式会新建然后再写入内容;文件存在时,w模式会清空文件再写入内容。
【3】文件的打开模式
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists

'b'       binary mode
't'       text mode (default)

'+'       open a disk file for updating (reading and writing)

The default mode is 'rt' (open for reading text).

关于文件的打开模式常见应用有:

  • 只读:rrtrb (用)
    存在,读
    不存在,报错

  • 只写:wwtwb(用)

    存在,清空再写
    不存在,创建再写

  • 只写:xxtxb(了解即可)

    存在,报错
    不存在,创建再写。

  • 只写:aatab【尾部追加】(用)

    存在,尾部追加。
    不存在,创建再写。

  • 读写

    r+、rt+、rb+,默认光标位置:起始位置

file_object = open('info.txt', mode='rt+')

# 读取内容
data = file_object.read()
print(data)

# 写入内容
file_object.write("你好呀")

file_object.close()

在这里插入图片描述

file_object = open('info.txt', mode='rt+')

# 写入内容
file_object.write("zhan")

# 读取内容
data = file_object.read()
print(data)  # 呀  此处从光标位置开始读取,故没有读取全部内容

file_object.close()

w+、wt+、wb+,默认光标位置:起始位置(清空文件)

file_object = open('info.txt', mode='wt+')

# 读取内容
data = file_object.read()   
print(data)

# 写入内容
file_object.write("你好呀")

# 将光标位置重置起始
file_object.seek(0)

# 读取内容
data = file_object.read()
print(data)

file_object.close()

x+、xt+、xb+,默认光标位置:起始位置(新文件)

a+、at+、ab+,默认光标位置:末尾

file_object = open('info.txt', mode='at+')

# 写入内容
file_object.write("张三")

# 将光标位置重置起始
file_object.seek(0)

# 读取内容
data = file_object.read()
print(data)

file_object.close()
【多用户注册案例】
while True:
    user = input("用户名:")
    if user.upper() == "Q":
        break
    pwd = input("密码:")

    data = "{}-{}\n".format(user, pwd)

    file_object = open('files/account.txt', mode='a')
    file_object.write(data)
    file_object.close()
file_object = open('files/account.txt', mode='a')

while True:
    user = input("用户名:")
    if user.upper() == "Q":
        break
    pwd = input("密码:")
    data = "{}-{}\n".format(user, pwd)
    file_object.write(data)

file_object.close()
【4】常见功能

在上述对文件的操作中,我们只使用了write和read来对文件进行读写,其实在文件操作中还有很多其他的功能来辅助实现更好的读写文件的内容。

  1. read,读
  • 读所有【常用】
f = open('info.txt', mode='r',encoding='utf-8')
data = f.read()
f.close()
f = open('info.txt', mode='rb')
data = f.read()
f.close()
  • 读n个字符(字节)【会用到】
f = open('info.txt', mode='r', encoding='utf-8')
# 读1个字符
data = f.read(1)
f.close()

print(data) # 你
f = open('info.txt', mode='r',encoding='utf-8')

# 读1个字符
chunk1 = f.read(1)
chunk2 = f.read(2)
print(chunk1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值