文件处理

1 文件打开模式补充

with open('a.txt', mode='r+t', encoding='utf-8') as f:
print(f.read())
print(f.writable())
print(f.readable())
f.write("你好") with open('a.txt', mode='w+t', encoding='utf-8') as f:
print(f.writable())
print(f.readable())
f.write("你好")
res = f.read()
print("===> %s" % res) with open('a.txt', mode='a+t', encoding='utf-8') as f:
print(f.writable())
print(f.readable())
print(f.read()) f.flush()
print(f.name)
print(f.encoding)

2.1 文件操作之读操作

with open('a.txt', mode='rt', encoding='utf-8') as f:
line1 = f.readline()
print(line1)
line2 = f.readline()
print(line2) for line in f:
print(line) lines = f.readlines()
print(lines)

2.2 文件操作之写操作

with open('a.txt', mode='wt', encoding='utf-8') as f:
f.write("1111\n2222\n3333\n") for x in "hello":
f.write(x) f.writelines("hello") # f.write("hello") f.writelines(["111", "222", "333"])
f.writelines(["111\n", "222\n", "333\n"])

3 控制文件指针移动

3.1 前提

  • 文件内指针移动,除了t模式下的read(n)中n代表的是字符个数

  • 其他都是以bytes为单位的

with open('a.txt', mode='rt', encoding='utf-8') as f:
res = f.read(6)
print(res) with open('a.txt', mode='rb') as f:
res = f.read(8)
print(res)
print(res.decode('utf-8')) with open('a.txt', mode='r+', encoding='utf-8') as f:
f.truncate(8)

3.2 f.seek()

  • f.seek(移动的字节个数,模式)

  • 三种模式

    0:参照文件开头移动指针

    1:参照当前所在的位置移动指针

    2:参照文件末尾位置移动指针

  • 只有0模式可以在t下使用,1和2只能在b下使用

with open('a.txt', mode='a+b') as f:
print(f.tell()) # 查看指针在文件的第几个字节 with open('a.txt', mode='r+b') as f:
f.seek(0, 2)
print(f.tell()) with open('a.txt', mode='a+b') as f:
f.seek(-6, 2)
# print(f.read().decode('utf-8'))
print(f.read(3).decode('utf-8')) import time with open('a.txt', mode='rb') as f:
f.seek(0, 2)
while True:
line = f.readline()
if len(line) == 0:
time.sleep(0.1)
else:
print(line.decode('utf-8'), end="")

4 文件修改的两种方式

4.1 方式一

1、以r模式打开源文件,将源文件内容全部读入内存

2、在内存中修改完毕

3、以w模式打开源文件,将修改后的内容写入源文件

优点:不必大量占用硬盘资源

缺点:耗内存,需要足够的内存空间

with open('a.txt', mode='rt', encoding='utf-8') as f1:
data = f1.read()
res = data.replace('hello', '早上好')
with open('a.txt', mode='wt', encoding='utf-8') as f2:
f2.write(res)

4.2 方式二

1、以r模式打开源文件,然后以w模式打开一个临时文件

2、从源文件中读一行到内存中,修改完毕后直接写入临时文件,循环往复直到操作完毕所有行

3、删除源文件,将临时文件名改为源文件名

优点:没有对内存造成过度的占用

缺点:需要硬盘预留出足够的空间来存放临时文件

import os
with open('a.txt', mode='rt', encoding='utf-8') as src_f,\
open('.a.txt.swp', mode='wt', encoding='utf-8') as dst_f: for line in src_f:
dst_f.write(line.replace('你好', 'Hello')) os.remove('a.txt')
os.rename('.a.txt.swp', 'a.txt')

5 函数的基本使用

5.1 概述

1、什么是函数?

函数就是用来盛放代码的容器

​ 具备某一功能的工具-->工具

​ 事先准备好工具的过程-->函数的定义

​ 遇到应用场景,拿来就用-->函数的调用

2、为何要用函数?

解决问题

Ⅰ 可读性差

Ⅱ 拓展性差

3、如何用函数?

先定义后引用

5.2 基本使用

def say_hello():  # say_hello=函数的内存地址
print("======")
print("hello world")
print("======") print(say_hello) # <function say_hello at 0x00000241DA0273A0>
say_hello() x = 10 # x=10的内存地址
print(x)

5.3 步骤

# 函数定义阶段:只检测语法,不执行代码
# def foo():
# xxx
# print('from foo') # 函数调用阶段:执行函数体代码
# foo()

5.4 示例

# 示例1
def bar():
print('from bar') def foo():
print('from foo')
bar() foo()
# 示例二
def bar():
print('from bar')
foo() def foo():
print('from foo') bar()
示例三
def bar():
print('from bar')
foo() bar() def foo():
print('from foo')

5.5 函数定义的完整语法

  • def 函数名(参数1, 参数2, 参数3...):

    '''

    注释信息

    '''

    代码1

    代码2

    代码3

    return 返回值

  • 定义函数的三种形式

无参函数
def f1():
print("hello")
print("你好")
print("Hi")
f1() def login():
name = input('username>>>:').strip()
pwd = input('password>>>:').strip()
if name == "ccc" and pwd == '111':
print('ok')
else:
print('error') login()
有参函数
def login(name,pwd):
if name == "ccc" and pwd == "123":
print('ok')
else:
print('error') login("ccc","123")
login("ccc","1234") def f2(x, y):
print(x)
print(y) f2(111, 222) def add(x, y):
print(x+y) add(10, 20)
add(30, 40)
空函数
def login():
pass
def transfer():
pass
def withdraw():
pass
def check_balance():
pass
  • 调用函数的三种形式
def add(x, y):
z = x + y
return z # res = add(10, 20)
# print(res)
# res = len("hello")
# print(res)
# 1、语句形式
len("hello") # 2、表达式形式
res = len("hello") + 10
print(res) # 3、函数调用可以当作一个参数传给另外一个函数
print(add(5, 5)) res = add(add(1, 2), 3)
print(res)

5.6 函数的返回值

  • return作用1:控制返回值
Ⅰ 没有return-->默认返回就是None
def func():
print(111) res = func()
print(res) Ⅱ return 值-->返回就是那一个值
def max2(x, y):
if x > y:
return x
else:
return y res = max2(100, 200) * 5
print(res) Ⅲ return 值1,值2,值3--->返回的是一个元组
def func():
return [11, 22], 2, 3 res = func()
print(res, type(res)) # ([11, 22], 2, 3) <class 'tuple'>
  • return作用2:函数内可以有多个return,但只要执行一个就会立即种植函数的运行,并且会将return后的值当做本次调用的产品返回
def func():
print(111)
return 2201202
print(2222)
return 11112222
print(3333) res = func()
print(res) # 111 2201202

附录:a.txt

早上好玛卡巴卡
早上好汤姆波利伯
早上好小点点
早上好依古比古
早上好唔西迪西
早安哈呼呼
早安鸟儿
Hello叮叮车
Hello飞飞鱼

最新文章

  1. jqgrid 中的事件
  2. php 之跨域上传图片
  3. Activity之间的数据传递
  4. C++ 排序函数 sort(),qsort()的含义与用法 ,字符串string 的逆序排序等
  5. 【剑指offer 面试题12】打印1到最大的n位数
  6. Android开发手记(7) 按钮类控件的使用
  7. android 模拟微信消息框 BaseAdapter()方法 [2]
  8. 资源预加载preload和资源预读取prefetch简明学习
  9. 【c#】RabbitMQ学习文档(六)RPC(远程调用)
  10. Unity3D 物体移动方法总结
  11. ionic编译安卓App
  12. 776. Split BST 按大小拆分二叉树
  13. learning ddr reset initialization with stable power
  14. pyhton字符串
  15. Python正则表达式(regular expression)简介-re模块
  16. 一个ssm综合小案例-商品订单管理----写在前面
  17. 使用chrome控制台作为日志查看器
  18. Centos7修改文件夹权限和用户名用户组
  19. netty SimpleChannelInboundHandler&lt;Message&gt;和ChannelInboundHandlerApter
  20. LeetCode解题报告—— Group Anagrams &amp; Pow(x, n) &amp; Spiral Matrix

热门文章

  1. 010_Java历史及特性
  2. 【踩坑系列】使用long类型处理金额,科学计数法导致金额转大写异常
  3. vue 组件传值,(太久不用就会忘记,留在博客里,方便自己查看)
  4. 如何实现一个FormData
  5. JAVA代码实现抖音短视频去水印功能
  6. eclipse中将java项目变成web项目
  7. Spring源码分析之`BeanFactoryPostProcessor`调用过程
  8. 【转】Setting up SDL 2 on Code::Blocks 12.11
  9. STM32入门系列-使用C语言封装寄存器
  10. yython爬虫基础知识入门