学习python的第七天

112 阅读2分钟

# # # open打开函数

import time

f = open("D:\测试\测试1.txt", 'r',encoding='utf-8')

print(type(f))

# 读取功能

# print(f"第一次读取的结果是:{f.read(5)}")

# print(f'第二次读取字节的结果:{f.read()}')

# print('----------------------------------------')

# lines = f.readlines()

# print(f'lines对象的类型是:{type(lines)}')

# print(f'lines的内容是:{lines}

# line1 = f.readline()

# line2 = f.readline()

# print(f'第一行数据是:{line1}')

# print(f'第二行数据是:{line2}')

# 循环读取文件

for line in f:

print(line)

# 关闭文件

# f.close()

# time.sleep(50000)

# with open语法操作文件

with open("D:\测试\测试1.txt", 'r',encoding='utf-8') as f:

for line in f:

print(f"每一行的数据师:{line}")

# time.sleep(50000)

小练习 统计文件中itheima出现了几次

f = open("D:\测试\测试2.txt", 'r',encoding='utf-8') count = 0 for line in f: if 'itheima' in line: count += 1 print(f'itheima出现了:{count}次') f.close()

小练习 用whiln统计文件中itheima出现了几次

f = open("D:\测试\测试2.txt", 'r',encoding='utf-8') count = 0 while True: line = f.readline() if not line: break if 'itheima' in line: count += 1 print(f'itheima出现了:{count}次') f.close()

读取全部内容,通过字符串count方法统计

f = open("D:\测试\测试2.txt", 'r',encoding='utf-8') content = f.read() count = content.count('itheima') print(f'itheima出现了:{count}次') f.close()

文件的写入操作

import time f = open('D://测试/测试3.txt', 'w', encoding='UTF-8') f.write('测试写入:Hello Python!') f.flush() f.close()

打开一个存在的文件 f = open('D://测试/测试3.txt', 'w', encoding='UTF-8') f.write('黑马程序员') f.close()

文件的追加操作

f = open('D://测试/测试3.txt', 'a', encoding='UTF-8') f.write("hello world\npython") f.close()

小练习 读取文件,见文件写出到测试5.txt作为备份 同时将文件内标记测试的数据行丢弃

f = open('D://测试/测试4.txt', 'r', encoding='UTF-8') i = open('D://测试/测试5.txt', 'w', encoding='UTF-8') for line in f: if '测试' in line: continue i.write(line) f.close() i.close()

# 打开一个不存在的文件

try:

f = open('D://测试/测试6.txt', 'r', encoding='UTF-8')

except:

print('文件不存在,我将open的模式,改为w模式打开')

f = open('D://测试/测试6.txt', 'w', encoding='UTF-8')

# # 捕获指定异常

try:

print(name)

except NameError as e:

print("你输入的变量名不存在")

print(e)

# 捕获多个异常

try:

1/0

print('name')

except (NameError,ZeroDivisionError) as e:

print('出现了变量未定义 或者 除以0的异常错误')

捕获所有异常

try: 1/0 except Exception as e: print('出现了异常错误') else: print("好高兴,没有异常错误") finally: print('无论是否出现异常错误,我都会执行') def func1(): print('func1 开始执行') num=1/0 print('func1 执行完毕') def func2(): print('func2 开始执行') func1() print('func2 执行完毕') def mian(): try: func2() except Exception as e: print(f'出现了异常错误,异常的信息是P{e}') mian()

模块的导入

import time print('你好') time.sleep(5) print('再见')

from time import sleep print('你好') sleep(3) print('再见')

from time import * print("你好") sleep(5) print("再见")

import time as t print('你好') t.sleep(5) print('再见')

from time import sleep as sl print("你好") sl(5) print("再见")