Python运维开发之路《文件处理》
一、python字典操作
1.字典的定义
字典一种key-value的数据类型,类似于json串。
2.字典的特性
key:value
字典不可变,key唯一
key的定义规则:
1.不可变,数字、字符串、字典、元组(定义符合(),与列表完全一致,唯一不同的是元组内元素不可变)
2.key必须是唯一的,所以字典天生有去重功能 value的定义规则:
1.任意数据类型
3.字典的使用方法
字典的增、删、改、查
1 查询:
2 print(dic['name'])
3 print(dic.get('name')) #get方法查询不存在的项不会报错
4
5 添加:
6 dic['gender'] = 'female' #k:v 无序添加
7
8 修改:
9 dic['name'] = '11' #key不可修改
10
11 删除:
12 del #万能删除
13 del dic['name'] #删除key
其他使用方法和函数调用
dicl = dict.fromkeys() #快速生成字典
dic.copy() #浅拷贝,只拷贝一层
dic.get() #值不存在不会报错
dic.items() #打印转换为列表形式
dic.keys() #取出字典中所有的key值
dic.pop() #pop删除,括号内写key,key不存在会报错
dic.popitem() #随机删除一对key.val
dic.setdefault() #添加字典
dic.update() #添加新字典,添加字典内容,修改字典内容
dic.values() #取出字典所有values值
字典的定义方法
字典的定义方法:
dic = dict() #空字典
dic1 = dict({'name':'alex','age':18})
print(dic1)
dic2 = dict(name='alex',age=18)
print(dic2)
dic3 = dict((('name','alex'),('age','18')))
print(dic3)
二、集合
1.集合的介绍
集合是一个无序的,不重复的数据组合,它的主要作用如下:
- 去重,把一个列表变成集合,就自动去重了
- 关系测试,测试两组数据之前的交集、差集、并集等关系
2.集合的操作方法
增加 add #添加元素到集合
update #添加集合到集合 随机删除 pop #随机删除
remove #指定删除,如果删除元素不存在,程序报错
discard #指定删除,如果删除元素不存在,报none 清空
clear #清空 差集并赋值
symmetric_difference_update #差集后,赋予新值
集合的几种模式
- 交集:intersection print(s1&s2)
- 并集:union print(s1|s2)
- 差集:difference print(s1-s2)
- 子集:issubset print(s1<=s2)
- 父集:issuperset print(s1>=s2)
- 对称差集:symmetric_difference print(s1^s2) #去掉两个集合里重复的
三、字符编码
1.在python2默认编码是ASCII, python3里默认是utf-8
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-8就是unicode
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
4.内存固定使用Unicode编码,硬盘的编码可以修改(即可以修改的软件编码)
5.使用什么编码往硬盘存,就用什么编码去读
6.程序运行分两个阶段:
- 从硬盘读到内存
- python解释器运行读到内存里的代码
7.针对.py文件,python与nodpad++\vim的区别是多了运行已经读到内存里的代码
四、python文件处理
1.关于python循环读取数据
文本文件:
1 Somehow, it seems the love I knew was always the most destructive kind
2 不知为何,我经历的爱情总是最具毁灭性的的那种
3 Yesterday when I was young
4 昨日当我年少轻狂
5 The taste of life was sweet
6 生命的滋味是甜的
7 As rain upon my tongue
8 就如舌尖上的雨露
9 I teased at life as if it were a foolish game
10 我戏弄生命 视其为愚蠢的游戏
11 The way the evening breeze
12 就如夜晚的微风
13 May tease the candle flame
14 逗弄蜡烛的火苗
15 The thousand dreams I dreamed
16 我曾千万次梦见
17 The splendid things I planned
18 那些我计划的绚丽蓝图
19 I always built to last on weak and shifting sand
20 但我总是将之建筑在易逝的流沙上
21 I lived by night and shunned the naked light of day
22 我夜夜笙歌 逃避白昼赤裸的阳光
23 And only now I see how the time ran away
24 事到如今我才看清岁月是如何匆匆流逝
25 Yesterday when I was young
26 昨日当我年少轻狂
27 So many lovely songs were waiting to be sung
28 有那么多甜美的曲儿等我歌唱
29 So many wild pleasures lay in store for me
30 有那么多肆意的快乐等我享受
31 And so much pain my eyes refused to see
32 还有那么多痛苦 我的双眼却视而不见
33 I ran so fast that time and youth at last ran out
34 我飞快地奔走 最终时光与青春消逝殆尽
35 I never stopped to think what life was all about
36 我从未停下脚步去思考生命的意义
37 And every conversation that I can now recall
38 如今回想起的所有对话
39 Concerned itself with me and nothing else at all
40 除了和我相关的 什么都记不得了
41 The game of love I played with arrogance and pride
42 我用自负和傲慢玩着爱情的游戏
43 And every flame I lit too quickly, quickly died
44 所有我点燃的火焰都熄灭得太快
45 The friends I made all somehow seemed to slip away
46 所有我交的朋友似乎都不知不觉地离开了
47 And only now I'm left alone to end the play, yeah
48 只剩我一个人在台上来结束这场闹剧
49 Oh, yesterday when I was young
50 噢 昨日当我年少轻狂
51 So many, many songs were waiting to be sung
52 有那么那么多甜美的曲儿等我歌唱
53 So many wild pleasures lay in store for me
54 有那么多肆意的快乐等我享受
55 And so much pain my eyes refused to see
56 还有那么多痛苦 我的双眼却视而不见
57 There are so many songs in me that won't be sung
58 我有太多歌曲永远不会被唱起
59 I feel the bitter taste of tears upon my tongue
60 我尝到了舌尖泪水的苦涩滋味
61 The time has come for me to pay for yesterday
62 终于到了付出代价的时间 为了昨日
63 When I was young
64 当我年少轻狂
lyrics
读取文件前5行:
#-*- coding:utf-8 -*-
data = open("lyrics",encoding='UTF-8') ##循环打印readlines,占用内存空间不推荐
for index,line in enumerate(data.readlines()):
if index < 5:
print(line)
else:
break ##循环打印readline
for i in range(5):
print(data.readline().strip()) ##循环打印for
count = 0
for line in data:
if count < 5:
print(line.strip())
count +=1
else:
break
2.python文件处理命令用法
基本的文件模式
1 #r,读模式,open命令默认是读模式
2 f = open('testfile','r',encoding='utf-8')
3 print(f.read())
4
5 #w,写模式
6 f = open('testfile','w',encoding='utf-8')
7 f.write('人生苦短,我学python\n')
8 f.close()
9
10 #a,追加模式
11 f = open('testfile','a',encoding='utf-8')
12 f.write('我呵呵你!\n')
13 f.close()
14
15 #删除,打开一个文件写入空即删除
16 f = open('testfile','r+',encoding='utf-8')
17 f.readline()
18 f.write('')
19
20 #r+,读写 可读,追加内容到最后
21 f = open('testfile','r+',encoding='utf-8')
22 f.readline()
23 f.write('devops\n')
24
25 #w+,写读 新建文件,写入再读取
26 f = open('testfile','w+',encoding='utf-8')
27 f.readline()
28 f.write('devops2\n')
29
30 # a+,追加读 清空源文件,再添加,然后读取
31 f = open('testfile','w+',encoding='utf-8')
32 f.readline()
33 f.write('devops3\n')
其他文件操作方法
f = open('testfile','w+',encoding='utf-8')
f.close()
f.closed    #判断操作的文件是否关闭
f.encoding  #打印文件的编码格式
f.fileno()  #返回操作系统接口文件索引<网络编程,I/O复用>
f.flush()   #刷新操作
f.isatty()  #判断打开的文件是否是终端文件
f.name      #打印文件名
f.newlines  #未读取到行分隔符时为 None,只有一种行分隔符时为一个字符串,当文件有多种类型的行结束符时,则为一个包含所有当前所遇到的行结束符的列表
f.readable()    #同isatty类似
f.seek()    #移动光标,到固定位置返回此位置以后的内容(按照字符移)
f.tell()    #打印光标所在位置的索引
f.truncate()    #截断,配合seek,括号内指定保留字符数量,从头开始切
f.writelines()  #写列表到文件
1 def close(self): # real signature unknown; restored from __doc__
2 """
3 Close the file.
4
5 A closed file cannot be used for further I/O operations. close() may be
6 called more than once without error.
7 """
8 pass
9
10 def fileno(self, *args, **kwargs): # real signature unknown
11 """ Return the underlying file descriptor (an integer). """
12 pass
13
14 def isatty(self, *args, **kwargs): # real signature unknown
15 """ True if the file is connected to a TTY device. """
16 pass
17
18 def read(self, size=-1): # known case of _io.FileIO.read
19 """
20 注意,不一定能全读回来
21 Read at most size bytes, returned as bytes.
22
23 Only makes one system call, so less data may be returned than requested.
24 In non-blocking mode, returns None if no data is available.
25 Return an empty bytes object at EOF.
26 """
27 return ""
28
29 def readable(self, *args, **kwargs): # real signature unknown
30 """ True if file was opened in a read mode. """
31 pass
32
33 def readall(self, *args, **kwargs): # real signature unknown
34 """
35 Read all data from the file, returned as bytes.
36
37 In non-blocking mode, returns as much as is immediately available,
38 or None if no data is available. Return an empty bytes object at EOF.
39 """
40 pass
41
42 def readinto(self): # real signature unknown; restored from __doc__
43 """ Same as RawIOBase.readinto(). """
44 pass #不要用,没人知道它是干嘛用的
45
46 def seek(self, *args, **kwargs): # real signature unknown
47 """
48 Move to new file position and return the file position.
49
50 Argument offset is a byte count. Optional argument whence defaults to
51 SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
52 are SEEK_CUR or 1 (move relative to current position, positive or negative),
53 and SEEK_END or 2 (move relative to end of file, usually negative, although
54 many platforms allow seeking beyond the end of a file).
55
56 Note that not all file objects are seekable.
57 """
58 pass
59
60 def seekable(self, *args, **kwargs): # real signature unknown
61 """ True if file supports random-access. """
62 pass
63
64 def tell(self, *args, **kwargs): # real signature unknown
65 """
66 Current file position.
67
68 Can raise OSError for non seekable files.
69 """
70 pass
71
72 def truncate(self, *args, **kwargs): # real signature unknown
73 """
74 Truncate the file to at most size bytes and return the truncated size.
75
76 Size defaults to the current file position, as returned by tell().
77 The current file position is changed to the value of size.
78 """
79 pass
80
81 def writable(self, *args, **kwargs): # real signature unknown
82 """ True if file was opened in a write mode. """
83 pass
84
85 def write(self, *args, **kwargs): # real signature unknown
86 """
87 Write bytes b to file, return number written.
88
89 Only makes one system call, so not all of the data may be written.
90 The number of bytes actually written is returned. In non-blocking mode,
91 returns None if the write would block.
92 """
93 pass
python2中源码解释
Python运维开发之路《文件处理》的更多相关文章
- python运维开发之路第一天
		一.python安装及环境变量配置 1.windows7安装python 1)下载地址:https://www.python.org/downloads/windows/ 如下图: 注意:下载,用代理 ... 
- Python运维开发基础09-函数基础【转】
		上节作业回顾 #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author:Mr.chen # 实现简单的shell命令sed的替换功能 import ... 
- Python运维开发基础08-文件基础【转】
		一,文件的其他打开模式 "+"表示可以同时读写某个文件: r+,可读写文件(可读:可写:可追加) w+,写读(不常用) a+,同a(不常用 "U"表示在读取时, ... 
- Python运维开发基础04-语法基础【转】
		上节作业回顾(讲解+温习90分钟) #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author:Mr.chen # 仅用列表+循环实现“简单的购物车程 ... 
- Python运维开发基础01-语法基础【转】
		开篇导语 整个Python运维开发教学采用的是最新的3.5.2版,当遇到2.x和3.x版本的不同点时,会采取演示的方式,让同学们了解. 教学预计分为四大部分,Python开发基础,Python开发进阶 ... 
- 重磅|0元学 Python运维开发,别再错过了
		51reboot 运维开发又双叒叕的搞活动了,鉴于之前 51reboot 的活动反馈,每次活动结束后(或者已经结束了很长时间)还有人在问活动的事情.这一次小编先声明一下真的不想在此次活动结束后再听到类 ... 
- Python运维开发基础01-语法基础
		标签(空格分隔): Mr.chen之Python3.0执教笔记(QQ:215379068) --仅供北大青鸟内部学习交流使用 开发不是看出来的,开发一定是练出来的: 想学好开发,没有捷径可走,只有不断 ... 
- Python运维开发基础10-函数基础【转】
		一,函数的非固定参数 1.1 默认参数 在定义形参的时候,提前给形参赋一个固定的值. #代码演示: def test(x,y=2): #形参里有一个默认参数 print (x) print (y) t ... 
- Python运维开发基础07-文件基础【转】
		一,文件的基础操作 对文件操作的流程 [x] :打开文件,得到文件句柄并赋值给一个变量 [x] :通过句柄对文件进行操作 [x] :关闭文件 创建初始操作模板文件 [root@localhost sc ... 
- Python运维开发基础06-语法基础【转】
		上节作业回顾 (讲解+温习120分钟) #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author:Mr.chen # 添加商家入口和用户入口并实现物 ... 
随机推荐
- SRS+Docker部署教程
			SRS+Docker部署教程 安装Docker Windows安装docker 安装Hyper-V Hyper-V 是微软开发的虚拟机,类似于 VMWare 或 VirtualBox,仅适用于 Win ... 
- mysql导出csv
			1.正常查询 SELECT a.emp_no '员工号',b.seq '文章序号' from vote_records a INNER JOIN vote_content b ON a.vote_co ... 
- 基于SqlSugar的开发框架循序渐进介绍(27)-- 基于MongoDB的数据库操作整合
			SqlSugar的开发框架本身主要是基于常规关系型数据库设计的框架,支持多种数据库类型的接入,如SqlServer.MySQL.Oracle.PostgreSQL.SQLite等数据库,非关系型数据库 ... 
- If选择语句的用法
			今天我们学习下If判断语句. 首先了解下它有几种用法: If单选择语句 If双选择语句 If多选择语句 我们一个一个用,每一个用法都给一个运用的过程演练一下. If单选择语句:我们很多需要判断一个东西 ... 
- MySQL 中常见的几种高可用架构部署方案
			MySQL 中的集群部署方案 前言 MySQL Replication InnoDB Cluster InnoDB ClusterSet InnoDB ReplicaSet MMM MHA Galer ... 
- 【源码分析】XXL-JOB的执行器的注册流程
			目的:分析xxl-job执行器的注册过程 流程: 获取执行器中所有被注解(@xxlJjob)修饰的handler 执行器注册过程 执行器中任务执行过程 版本:xxl-job 2.3.1 建议:下载xx ... 
- 关于windows11  开启关闭管理员账户
			如何在Windows 11上启用或禁用管理员帐户 当 PowerShell 启动时,键入以下命令并按Enter: net user administrator /active:yes 在 Window ... 
- Godot 4.0 文件读取(C#)
			搞半天才弄明白Godot文件操作. Godot的文档总是试图让我使用自定义Resource来支持文件操作,但是我只需要读取纯文本. 读取纯文本 读取纯文本的方式如下: //Godot.FileAcce ... 
- 在基于nuxt的移动端页面中引用mint UI的popup组件之父子组件传值
			最近在做移动端的wap页面,考虑到要做SEO,所以选定了nuxt+vue+mint ui. 有一个需求是这样的,点击头部菜单栏,出现一个气泡,点击返回首页. 由于一些页面没有统一引用mint的mt-h ... 
- 2022-10-05:在一个 n x n 的整数矩阵 grid 中, 每一个方格的值 grid[i][j] 表示位置 (i, j) 的平台高度。 当开始下雨时,在时间为 t 时,水池中的水位为 t 。
			2022-10-05:在一个 n x n 的整数矩阵 grid 中, 每一个方格的值 grid[i][j] 表示位置 (i, j) 的平台高度. 当开始下雨时,在时间为 t 时,水池中的水位为 t . ... 
