8.8 day11

Advanced application file

Advanced application file can be read but also write can do (try not to use)

r+

r + is additionally written after the original document

# test.py 文件内容为 '''111'''

with open('test.py', 'r+', encoding='utf8') as fr:
    data = fr.read()
    print(fr.writable())
    fr.write('x = 10')
    print(data)
结果为:
True
'''111'''

File content becomes '' '111' '' x = 10

Note that there is no data at this time to print x = 10 because it has been read before writing

w+

Empty file function is provided by W, w + not to use

In other words, the culprit f.write () is not empty file

with open('test.py', 'w+', encoding='utf8') as fr:
    print(fr.readable())
    fr.write('x = 10')
文件结果变为x = 10
with open('test.py', 'w+', encoding='utf8') as fr:
    # print(fr.readable())
    # fr.write('x = 10')
    data =  fr.read()
    print(data)

The file is nothing but the result is not can not read, but this time has been file with nothing. If you ask why, it is to be cleared w

a+

a + is also read in the case originally added

with open('test.py', 'a+', encoding='utf8') as fr:
    data = fr.read()  
    print(data)

    fr.write('x = 10')
    fr.flush()

This time you will find that print is still nothing, but there is no clear wondering a text that way? And after many print found, txt file x more and more, but it does not print anything. Here on issues related to a pointer, I will elaborate in the next one by one

pointer

File pointer is a built-in method, in fact, that is, when you click on a line when the word, is a glowing vertical pointer. So the question back to the top, why obviously there is data in the text, but read () but it could not be read? This is because the read function is started reading pointer from the place, and a + default pointer is at the end of the file, so naturally did not reproduce here. It said before the first run in read-only mode can only be read once also the same reason.

seek

After changing the position of the pointer for reading

with open('test.py', 'rb') as fr:
    fr.seek(1)  # 1表示位移1位,默认从文件头开始
    fr.seek(1, 0)  # 1表示偏移1位,0表示从头开始(这里和第一个一样)
    fr.seek(2, 1)  # 1表示偏移1位,1表示从当前位置开始
    fr.seek(0, 2)  # 0表示偏移0位,2表示文件末开始,把指针移到文件末
    print(fr.read())
结果依次为:
b' = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10'
b' = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10'    
b' 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10x = 10'
b''

Therefore, after fitting seek, a + files can be read

with open('test.py', 'a+', encoding='utf8') as fr:
    fr.seek(1, 0)
    data = fr.read()
    print(data)

    fr.write('x = 10')
    fr.flush()

tell

To tell you the same position of the pointer

with open('test.py', 'r', encoding='utf8') as fr:
    fr.seek(2, 0)
    print(fr.tell())    # 2

read(n)

Bytes in the file can be read

with open('test.py', 'r', encoding='utf8') as fr:
    print(fr.read(5))   # x = 1
    print(fr.read(6))   # x = 10 

truncate truncate

Read-only mode can not be used. Write-only mode will clear the file, it is generally used in append mode

with open('test.py', 'a', encoding='utf8') as fr:
    fr.truncate(2)  # 将 x 后的内容全部清空

File modification of two ways

First, the file did not actually modify this statement, this statement only cover

Because around this text in your document, in fact, he might have kept the full of something else. If you add something in this text, which means that all memory must be moved back a few cells, it is unscientific.

Instead of the usual time to modify the file, all simulated results, specifically implemented in two ways.

method one

import os

with open('test.txt') as fr, \
        open('test_swap.txt', 'w') as fw:
    data = fr.read()  # 全部读入内存,如果文件很大,会很卡
    data = data.replace('tank', 'tankSB')  # 在内存中完成修改

    fw.write(data)  # 新文件一次性写入原文件内容

# 删除原文件
os.remove('test.txt')
# 重命名新文件名为原文件名
os.rename('test_swap.txt', '37r.txt')
print('done...')

Second way

import os

with open('37r.txt') as fr,\
        open('37r_swap.txt', 'w') as fw:
    # 循环读取文件内容,逐行修改
    for line in fr:
        line = line.replace('jason', 'jasonSB')
        # 新文件写入原文件修改后内容
        fw.write(line)

os.remove('37r.txt')
os.rename('37r_swap.txt', '37r.txt')
print('done...')

总而言之,修改文件内容的思路为:以读的方式打开原文件,以写的方式打开一个新的文件,把原文件的内容进行修改,然后写入新文件,之后利用os模块的方法,把原文件删除,重命名新文件为原文件名,达到以假乱真的目的

函数

定义函数的方式

def 函数名():  # 定义阶段(造车轮阶段)
    """函数注释写在这里"""  # 函数相当于工具, 注释相当于工具的说明书
    <代码块>

# 使用  # 调用阶段(开车阶段)
函数名()

def func():
    """func函数的注释"""
    # todo:未来写一个开车函数
    pass
func()

注意:函数在定义阶段的时候不执行函数整体代码,智能检测到语法错误

print(func.__doc__)
可以知道函数中的注释

函数的简单实例

我们不妨尝试用函数来实现登录注册功能

def register():
    """注册函数"""
    username = input('请输入你的用户名:')
    pwd = input('请输入你的密码:')

    with open('user_info.txt', 'a', encoding='utf8') as fa:
        fa.write(f'{username}:{pwd}|')
def login():
    """登录函数"""
    username = input('请输入你的用户名:')
    pwd = input('请输入你的密码:')

    with open('user_info.txt', 'r', encoding='utf8') as fr:
        data = fr.read()
        user_list = data.split('|')
        print(user_list)
        user_info = f'{username}:{pwd}'
        if user_info in user_list:
            print('登录成功')
        else:
            print('傻逼,密码都忘了')

有没有发现,当函数没有参数的时候,里面的代码块和在外面打的没有什么区别。其实,函数更多的是一种思想,而不是一种技术

函数的三种定义方式

三种方式分别为无参函数,有参函数,空函数

无参函数

def add():
    """无参函数"""
    x = input('num1:')
    y = input('num2:')

    print(int(x) + int(y))

无参函数可以进行单独使用,上面的登录注册也是同理

有参函数

有参函数在函数中增加了参数,再往函数中输入参数之后才能使用

def add(x, y): 
    """有参函数"""
    print(int(x) + int(y))


print(1)
x = input('num1:')
y = input('num2:')
add(x, y)

结果为:
num1:1
num2:2
3

空函数

顾名思义,里面什么都没有

当你不知道函数怎么写的时候,可以先放一边,等以后再来写

def func():  # 只知道工具叫什么名字,但不知道如何造出这个工具
    pass

函数的调用

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


res = add(10, 20)  # 函数的调用
print(res*12)   # 360

这就是函数简单的调用,无参函数一般都是直接执行func(),有参函数则要在括号中输入符合要求的参数

函数的返回值

函数的返回值就是return,当函数执行到return时,直接返回return后面的数值,有一点类似于break的用法,可以配合if函数的使用来返回多种情况的值

def add(x, y):
    return (x, y, x + y)  # return可以返回任意数据类型
    return x, y, x + y  # return可以返回任意数据类型,不加括号返回多个值时,默认用元祖的形式返回

到这里函数的基础部分已经结束了。函数并不难,只要多敲几遍熟悉熟悉,相信马上就能熟能生巧

Guess you like

Origin www.cnblogs.com/hyc123/p/11322285.html