2020-11-10

关于python的第二篇笔记

1.文件的定义被持久化存储在磁盘上的字符串2.文件的操作
1)读操作:将文件中的字符串加载进内存2)写操作:将字符串写入到磁盘中的操作例如:open函数用于读写文件

print(help(open))

3.参数
1)file:文件名
注意路径:绝对路径 r"C:\test\hello.txt" 相对路径 next\hello. txt
2)encoding:指定open函数在读写文件时使用 的字符集
windows 默认字符集是gbk notepad++ 默认字符集是utf-8
open函数在windows上默认字符集是gbk,在Linux上 默认字符集是utf-8,open函数执行后返回一个对象文件
3)mode:
“r” 只读模式(默认)
"w"只写模式,文件不存在可以创建文件,文件存在时覆盖文件
"a"追加模式,文件不存在创建文件,文件存在时将内容添加到文件末尾
4.文件对象read( )方法默认将文件中所有字符串读取到内存,也可以根据字符个数读取read(n)[n表示字符个数]。
文件中的换行也占一个字符,使用\n表示readline( ) 按行读取数据readlines( ) 将所有数据按行存放到列表中

f=open(r"D:\python\test.txt",mode="r",encoding="utf-8")
foods = f. readlines()
f. close()

print(foods)

foods. insert(1,"蛋糕\n")

writelines(list) 将列表中字符串直接写入到文件
write(string)将字符串写入到文件

f=open(r"D:\python\test.txt",mode="w",encoding="utf-8")
f. write lines(foods)
f. write("苹果\n桃子\n葡萄\n草莓\n")
f. close()

5.加载词库

def load_word(file):
    print("开始加载数据…")
    f = open(file,encoding="utf-8") 
    data = f. readlines()
    f. close()    
    print("加载成功!")    
    return data    
    
def find_word():    
   data = load_word("word.txt")
   while True:                  
       w = input("请输入您要查询的内容,输入Q退出:")        
       if w =="Q":            
           break        
       n = 0        
       for line in data:            
           if w in line:                
               n += 1                         
               print(n,line,end="")
   
find_word()
input()

6.模块的定义
.py文件,所有的python脚本都可以作为python模块被调用
7.包:存放有相互关联的一组python模块的文件夹,例如:init_.py文件
*从包中引用所有模块或从模块中引用所有的函数和变量
8.pyc:经过python编译后的py模块文件,执行速度更快

import p1
print(p1.a+p1.b)
p1.hello()

from p1 import a,b
from p1 import hello as h

print(a,b,a+b)
h()

from tools. p1 import hello
hello()

9.模块的类型
内置模块 自定义模块 第三方模块
#sys是python内置模块,修改或调用python解释器的方法

import sys

#将模块的所在路径添加到python的模块路径中

print(system.path)system. path. append("d:\\")

#pip命令可以下载安装第三方模块
安装 pip install 模块名
卸载 pip uninstall 模块名
查看 pip list
10.模块的调用
.py文件就是一个模块 使用关键字 import或from xxx import xxx 引用模块

import m1
print(m1.a,m1.b,m1.a+m1.b)
m1.hello()
from m1 import hello,a,b

hello()
print(a,b,a+b)

#使用包

import bao
from bao. m1 import hello

hello

关于python的第二篇笔记就到此结束了!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值