一、文件操作

1.文件操作的处理流程

  打开文件得到文件句柄并赋值给一个变量====》通过句柄对文件进行分析====》关闭文件

#1. 打开文件,得到文件句柄并赋值给一个变量
f=open('Lakers.txt','r',encoding='utf-8') #默认打开模式就为r #2. 通过句柄对文件进行操作
data=f.read() #3. 关闭文件
f.close()

  为了避免忘记关闭文件,可以用with open

#读
with open("Lakers.txt", "r", encoding="utf-8") as f:
data = f.read()
print(data)
#写
with open("Lakers.txt","r",encoding="utf-8") as f1, \
open("Spurs.txt","w",encoding="utf-8") as f2:
data1 = f1.read()
f2.write("tim\n21\n未来是你的")
print(data1)

  文件打开时指定的编码要和保存时指定的编码相同,否则会出现乱码。

2.打开文件的模式

(1)打开文件的模式

  打开文件的模式(默认为文本模式):只读(r),只写(w),只追加(a)

(2)非文本模式

  对于非文本模式,只能用b模式,“b”表示以字节的方式操作,rb,wb,ab。b模式不需要考虑文本文件的字符编码、图片、视频的格式等,读取的内容是字节类型,写入时也要指定字节类型,不能指定编码。

a.文件模式

  r 读模式,默认的模式

f = open("Lakers.txt","r",encoding="utf-8")
data = f.read()
print(data)

  w 写模式,写之前会创建新的文件,如果文件存在,内容会被覆盖

f = open("Lakers.txt","w",encoding="utf-8")
f.write("kobe byrant\n24&8\n湖人总冠军")
f.close()

  a 写模式,在文件最后追加内容

f = open("Lakers.txt","a",encoding="utf-8")
f.write("老子库兹马,又帅又能打")
f.close()

b.binary mod,二进制模式

  b的方式读

f = open("Lakers.txt","rb")
data = f.read()
print(data)
print(data.decode("utf-8"))
f.close()

  b的方式写

f = open("Spurs.txt","wb")
f.write(bytes("马刺马刺马刺\nTim Duncon\n未来是你的",encoding="utf-8"))
f.close()

c.t text mod,文本模式

d.+ open a disk file for updating (reading and writing)

e.U universal newline mode (for backwards compatibility; should not be used in new code)\r\n

f = open("Spurs.txt","r",encoding="utf-8",newline="")
data = f.readlines()
print(data

3.文件的操作

(1)f.read()  

  读取文件的全部内容,光标移动到文件的末尾 

(2)f.readline()

  读取文件的一行内容,光标移动到文件下一行开头

with open("Lakers.txt","r",encoding="utf-8") as f:
data1 = f.readline()
data2 = f.readline()
data3 = f.readline()
data4 = f.readline()
# data5 = f.readline()
print(data1,data2,data3,data4)

(3)f.readlines()  

  读取每一行内容,存放于列表中

with open("Lakers.txt","r",encoding="utf-8") as f:
data1 = f.readlines()
print(data1)

(4)f.write()

(5)f.writelines()

with open("Spurs.txt","a",encoding="utf-8") as f:
f.writelines(["\nkawaii\n","张铁林\n","张继科\n"])

(6)

  f.readable()  判断文件是否可读

  f.writable()  判断文件是否可写??

  f.closed()  判断文件是否关闭

  f.flush()  将文件从内存刷新到硬盘

4.光标移动

  f.read(n) 文本模式下移动n个字符,b模式下移动n个字节

  f.seek(n) 任何模式下都是移动n个字节

  offset -- 开始的偏移量,也就是代表需要移动偏移的字节数

  whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。1和2必须在b模式下

f = open("Lakers.txt","rb")
f.seek(3,0)
print(f.tell())
f.seek(3,1)
print(f.tell())
f.seek(-3,2)
print(f.tell())

  f.truncate(n) 截取n个字节

  f.tell() 显示光标当前位置

二、一个文件操作系统

# 实现功能:1.函数操作 2.文件处理 3.tag的用法 4.文件的解耦
import os
def file_handler(backend_data,res=None,type="fetch"):#文件的解耦
if type == "fetch":
with open("haproxy.conf","r") as read_f:
tag = False#tag用法
ret= []
for read_line in read_f:
if read_line.strip()==backend_data:
tag =True
continue
if tag and read_line.startswith("backend"):
break
if tag:
print(read_line,end="")
ret.append(read_line)
return ret
elif type == "change":
with open("haproxy.conf", "r") as read_f, open("haproxy.conf_new", "w") as write_f:
tag = False
has_write = False
for read_line in read_f:
if read_line.strip() == backend_data:
tag = True
continue
if tag and read_line.startswith("backend"):
tag = False
if not tag:
write_f.write(read_line)
else:
if not has_write:
for record in res:
write_f.write(record)
has_write = True
os.rename("haproxy.conf", "haproxy.conf.bak")
os.rename("haproxy.conf_new", "haproxy.conf")
os.remove("haproxy.conf.bak")
def fetch(data):
print("这是查询功能")
print("用户数据是",data)
backend_dat= "backend %s" %data
return (file_handler(backend_dat)) def add():
pass def change(data):
backend=data[0]["backend"]
backend_data="backend %s" %backend
old_server_record="%sserver %s %s weight %s maxconn %s\n" %(" "*8,data[0]["record"]["server"],
data[0]["record"]["server"],
data[0]["record"]["weight"],
data[0]["record"]["maxconn"])
new_server_record="%sserver %s %s weight %s maxconn %s\n" %(" "*8,data[1]["record"]["server"],
data[1]["record"]["server"],
data[1]["record"]["weight"],
data[1]["record"]["maxconn"])
print("用户想要修改的记录是:",old_server_record)
res = fetch(backend)
print("来自change函数读取的内容:",res)
if not res or old_server_record not in res:
print("没有找到要修改的内容")
else:
index = res.index(old_server_record)
res[index]=new_server_record
res.insert(0,"%s\n" %backend_data)
file_handler(backend_data,res=res,type="change")
return res def delete():
pass if __name__ == "__main__":#判断功能
msg='''
1:查询
2:增加
3:修改
4:删除
5:退出
'''
msg_dic={
"":fetch,
"":add,
"":change,
"":delete,
}
while True:
print(msg)
choice = input("请输入你的选项: ").strip()
if not choice:continue
if choice == "": break data = input("请输入你的数据:").strip()
if choice != "":
data = eval(data) res = msg_dic[choice](data)
print(res)
# [{"backend":"www.oldboy1.org","record":{"server":"2.2.2.4","weight":"20","maxconn":"3000"}},{"backend":"www.oldboy1.org","record":{"server":"2.2.2.5","weight":"20","maxconn":"3000"}}]

文件操作系统

Python开发——6.文件操作的更多相关文章

  1. python开发_python文件操作

    关于python文件操作的详细说明,大家可以参考:关于python的文件操作 官方API:os-Miscellaneous operating system interfaces 下面是我做的demo ...

  2. 05 python开发之文件处理

    05 python开发之文件处理 目录 05 python开发之文件处理 5 文件处理 5.1 字符编码 5.1.1 基本概念 5.1.2 发展历程 5.1.3 使用 5.2 文件处理基础 5.2.1 ...

  3. python os&shutil 文件操作

    python os&shutil 文件操作 # os 模块 os.sep 可以取代操作系统特定的路径分隔符.windows下为 '\\' os.name 字符串指示你正在使用的平台.比如对于W ...

  4. python 历险记(三)— python 的常用文件操作

    目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...

  5. Python的高级文件操作(shutil模块)

    Python的高级文件操作(shutil模块) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果让我们用python的文件处理来进行文件拷贝,想必很多小伙伴的思路是:使用打开2个 ...

  6. Python入门篇-文件操作

    Python入门篇-文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.文件IO常用操作 open:打开 read:读取 write:写入 close:关闭 readlin ...

  7. python基础篇(文件操作)

    Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...

  8. Python之常用文件操作

    Python之常用文件操作

  9. Python开发【第三篇】:Python基本之文件操作

    Python基本之文本操作 一.初识文本的基本操作 在python中打开文件有两种方式,即:open(...) 和  file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open ...

随机推荐

  1. python3对excel文件读写操作

    ===========================excelfile文件============================================ ================= ...

  2. 【函数】raise 函数(小窗help)

    在Python中,要想引发异常,最简单的形式就是输入关键字raise,后跟要引发的异常的名称. 异常名称标识出具体的类: Python异常处理是那些类的对象. 执行raise语句时,Python会创建 ...

  3. leetcode136

    public class Solution { public int SingleNumber(int[] nums) { Dictionary<int, int> dic = new D ...

  4. 最适合入门的Laravel中级教程(四)前端开发

    Laravel 使用 npm 安装前端依赖: npm 是一个类似 composer 的工具: 用于管理前端的各种依赖包: 在使用之前需要先安装 node : Windows 下可以在官网下载安装: h ...

  5. IDEA 工具从Json自动生成JavaBean

    1.先安装GsonFormat插件:File-->Setting-->Plugins-->GsonFormat-->OK 2.new 一个新的Class空文件,然后 Alt+I ...

  6. 安装SourceTree工具,无需注册就可以正常使用SourceTree

    1. 下载SourceTree安装包 2. 双击安装包进行安装,默认会直接安装在系统盘,此时桌面就会SourceTree的快捷键 3. 双击打开桌面的SourceTree,就会提示让你安装授权,那么接 ...

  7. Modelsim command line 传参数到 .do 文件

    gui跑mdelsim总觉得很麻烦,使用命令来启动方便了很多,类似linux一样,其实目前windows也可以做到,只是业界不怎么用windows罢了. 基于modelsim搭了一个UVM环境,  用 ...

  8. java学习笔记(十一):重写(Override)与重载(Overload)

    重写(Override) 重写是子类对父类的允许访问的方法的进行重新编写, 但是返回值和形参都不能改变. 实例 class Animal{ public void run(){ System.out. ...

  9. yum方面的知识

    修改CentOS默认yum源为国内yum镜像源 1.mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bac ...

  10. 【Nodejs】Expressのサンプルについて

    全体の実行命令: ①c:\workspace>node XXX.js ②ブラウザに「http://localhost:3000」を入力 ▲サンプル① ・ソース(express_demo.js) ...