python文件操作,模块、包

文件读取操作

# 打开文件 open(name, mode, encoding) r:只读,w:写入,原有内容会清除,若不存在则创建。a:打开文件用于追加,若不存在则创建
f = open("ceshi.txt", "r", encoding="utf-8")
print(type(f))
# 读取文件 read(num),读取指定长度字节,未传入则读取全部数据
st = f.read(1)
print(st)
# readlines() ,按照行的方法把文件一次性读取
ss = f.readlines()
print(ss) # ['23\n', '456\n', '7889']
print("----------------------------------")
# readline() 一次读一行
f = open("ceshi.txt", "r", encoding="utf-8")
ss = f.readline()
print(ss)
# for循环读取文件行
for line in f:
    print(line)
time.sleep(3)
# 文件关闭 close()
f.close()
# with open 语法操作文件,运行完自动关闭文件
with open("ceshi.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line)

文件写入

f = open("ceshi.txt", "w", encoding="utf-8")
f.write("我爱你") # 只是写在缓冲区
# 内容刷新
f.flush() # 内容真正写入
f.close()
# 文件追加
f = open("ceshi.txt", "a", encoding="utf-8")
f.write("\n亲爱的")
f.flush()
f.close()

异常、模块、包

try:
    f = open("cs.txt", "r", encoding="utf-8")
except:
    print("文件不存在")
# 捕获指定异常
try:
    print(name)
except NameError as e:
    print("出现了变量未定义")
    print(e)
# 捕获多个异常
try:
    1/0
except (NameError, ZeroDivisionError) as e:
    print("出现了变量未定义或者除0的异常")
# 捕获所有异常
try:
    1/0
except Exception as e:
    print("出现异常了")
# ------------------------------------------------------
try:
    print("123")
except Exception as e:
    print("出现异常了")
else:
    print("没有异常")
# ----------------------------------------------
try:
    print("123")
except Exception as e:
    print("出现异常了")
else:
    print("没有异常")
finally:
    print("无论是否有异常都要执行finally")

异常具有传递性。

def func1():
    print("f1执行")
    num = 1/0  # 肯定有异常
    print("func1结束")
def func2():
    print("f2执行")
    func1()
    print("func2结束")
def main():
    try:
        func2()
    except Exception as e:
        print(f"出现异常了,{e}")
main()  # f2执行 f1执行 出现异常了,division by zero

python的模块

模块导入

[from 模块名] import [模块|类|变量|函数|*] [as 别名]

# 使用import导入time模块使用sleep
import time
print("1")
time.sleep(1)  # 睡眠 1s
print("2")
# 使用from导入time功能
from time import sleep
print("3")
sleep(1)  # 睡眠 1s
print("4")

# 使用* 导入time模块全部功能
from time import *  # *表示全部
print("5")
sleep(1)  # 睡眠 1s
print("6")

# 使用as加别名,防止模块名过长
import time as t
print("7")
t.sleep(1)  # 睡眠 1s
print("8")

自定义模块

def test(x, y):
    return x+y

import my_model01 as m1
a = int(input())
b = int(input())
res = m1.test(a, b)
print(f"结果是:{res}")

python包

物理上是文件夹

# 导入包
import my_package.my_model1
from my_package import my_model1

安装第三方包:使用pip程序

打开命令提示符,输入:pip install 包名

install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值