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 # 添加商家入口和用户入口并实现物 ...
随机推荐
- 利用NGINX搭建部署直播流媒体服务器
直播如今是一个老生常谈的问题,怎么用于直播,大多数人只晓得,大佬某平台直播软件,点击开始即可直播.那么如何来搭建一个简易的直播平台呢?仅仅是有直播功能,没有涉及转码以及播放软件. 安装nginx以及r ...
- 华为 A800-9000 服务器 离线安装MindX DL 可视化环境+监控
MindX DL Sample主要应用于企业的数据中心或超算中心机房中,针对不同的应用场景为客户提供AI深度学习端到端解决方案. 传统行业:用户无自建深度学习平台,希望能够提供简单易用.软硬件一体化的 ...
- python程序,实现以管理员方式运行程序,也就是提升程序权限
quest UAC elevation from within a Python script? 我希望我的Python脚本能够在Vista上复制文件. 当我从普通的cmd.exe窗口运行它时,不会生 ...
- windows10设置共享目录
win10设置目录局域网内共享 1.右键点击文件属性,点击共享 2.选择与其共享的用户 3.点击共享,选择everyone,可以让在同一局域网下的用户访问 4.显示你的文件夹已共享 5.在同一局域网的 ...
- c/c++零基础坐牢第二天
c/c++从入门到入土(2) 开始时间2023-04-13 23:02:34 结束时间2023-04-14 01:26:05 前言:如果第一天没把你劝退,恭喜你!通过今天的学习你就能半步踏进编程的大门 ...
- 注解:@RequiredArgsConstructor、 @Validated、 @Valid、 @Lazy
1. lombok注解:@RequiredArgsConstructor Spring 依赖注入方式 1.通过 @Autowire.@Resource 等注解注入, 2.通过构造器的方式进行依赖注入. ...
- Typora 隐藏侧边栏图片文件夹
前言 在使用 Typora 的时候,我将图片的保存路径设置为了如下所示: 这样设置是为了更方便的管理笔记中的图片,但图片文件夹却也显示在了侧边栏中,随着笔记增多,我的侧边栏越来越乱... 难道要忍气吞 ...
- Python 项目:外星人入侵--第三部分
1.项目内容: 在屏幕左上角添加一个外星人,并指定合适的边框,根据第一个外星人的边距和屏幕尺寸计算屏幕上可容纳多少个外星人. 让外星人群向两边和下方移动,直到外星人被全部击落,有外星人撞到飞船,或有外 ...
- 深度学习-09(目标检测:Object Detection)
文章目录 目标检测(Object Detection) 一 .基本概念 1. 什么是目标检测 2. 目标检测的核心问题 3. 目标检测算法分类 4. 目标检测应用 目标检测原理 1.候选区域产生 1 ...
- Grafana 系列-统一展示-2-Prometheus 数据源
系列文章 Grafana 系列文章 Grafana Prometheus 数据源 Grafana 提供了对 Prometheus 的内置支持.本文会介绍 Grafana Prometheus(也包括 ...