python文件操作
python学习日记-day19
文件操作流程 3步:
1. 打开文件
open()
2. 操作文件
read(), write()
3. 关闭文件
close()
--------读操作----------
默认模式为 r
f = open("test.txt", encoding="UTF-8")
content = f.read() # 读取所有字符
print(content)
f.close()
f = open("test.txt", encoding="UTF-8")
content2 = f.read(3) # 从光标位置 读指定个数的字符,python2读的是字节,python3读的是字符
print(content2) # 这里没有结果打出,因为上面的read() 已经将所有内容读出了
f.close()
f = open("test.txt", encoding="UTF-8")
content3 = f.readline() # 读一行,多行时为第一行
print(content3)
f.close()
f = open("test.txt", encoding="UTF-8")
content4 = f.readlines() # 取到的是一个列表结果
print(content4)
f.close()
f = open("test.txt", encoding="UTF-8")
content5 = f.readable() # 判断文件是否可读,返回True和False
print(content5)
f.close()
----------读练习----------
需求:打印出文件里的内容,在第4行后面加上“岳飞”两个字
# 方式一:
f2 = open("test.txt", encoding="UTF-8")
count = 0
for line in f2.readlines():
if count == 3:
line = "".join([line.strip(), "岳飞"]) # 当读到第4行时再结尾加入“岳飞”
print(line.strip())
count += 1
f2.close()
建议写为这样:
区别在于 for line in f2.readlines(): 和 for line in f2:
使用f2.readlines()的效果和f2的效果一样,但是不要用。因为他是把所有内容分行读到内存中存储再操作,文件大的话资源开销很严重,
而f2是一个文件对象,是按行序列的,也是一个迭代器,line是取一行操作一行,取第2行时,第一行所占用的内存就自动被回收掉了,不会占用额外内存
# 方式二:
f2 = open("test.txt", encoding="UTF-8")
count = 0
for line in f2:
if count == 3:
line = "".join([line.strip(), "岳飞"]) # 当读到第4行时再结尾加入“岳飞”
print(line.strip())
count += 1
f2.close()
-----------写操作----------
# mode默认为r,赋值为w时就只能写,不能读。
f3 = open("test2.txt",mode="w",encoding="UTF-8")
f3.write("Hello") # 将内容写入到test2.txt文件,有文件test2.txt就覆盖里面的内容,没有就创建文件并写入内容
f3.close()
# mode为a 表示是追加模式,会在文件末尾追加内容
f4 = open("test3.txt",mode="a",encoding="UTF-8")
f4.write("world")
f4.close()
# mode为x时,创建文件并写入内容,如果文件存在会报错
f13 = open("test13.txt",mode="x",encoding="UTF-8")
f13.write("Hello")
f13.close()
# ------------flush操作-------------
f5 = open("test4.txt",mode="w",encoding="UTF-8")
f5.write("this test5")
f5.flush() # 立刻将缓存中的内容写到磁盘
import time # 引入time模块
time.sleep(30) # 睡眠30秒
f5.close()
-----------可读可写----------
可读可写模式有:r+ w+ a+
# r+ 可读可写,读的时候文件不存在会报错,写的时候是追加写
f = open("test3.txt",mode="r+",encoding="UTF-8")
print(f.read())
f.write("im test")
f.close()
# w+ 可读可写,当读的时候读不到内容,因为文件打开是首先会将文件内容清除,然后再读或写
# 当第一次读的时候文件已经清空,所以读不到
# 当写入内容后再读,也读不到,因为光标已经在文件末尾了,所以读不到,但文件是已经写入了的,可通过seek(0)将光标移到开头来读
f = open("test3.txt", mode="w+", encoding="UTF-8")
print(f.read())
f.write("imtest中国")
f.seek(0) # 将光标移到第0个字节,即可从头开始显示,seek(3)移动到第3个字节,seek()是按字节的移动的,不是按字符的,不同于read(0)
print(f.tell()) # tell() 返回当前在哪个字节
print(f.read())
f.close()
#补充:
# seek(-3,2) 第二个参数有三个模式:0:光标从头开始数,1:光标从当前开始数,2:光标从后开始数。
# 当模式为2时一定要按字节操作,如打开文件模式设为rb,wb
# 第一个参数表示移动多少个字节
f.seek(-3,2) # 表示从后往前数移动3个字节
f = open("test3.txt", mode="rb")
print(f.read())
f.seek(-3, 2)
print(f.tell()) # tell() 返回当前在哪个字节
print(f.read())
f.close()
# a+ 可读可写,不清空直接从光标后开始写,光标自动调到最后了,所以read()不出来,需要seek(0)
# a+无论光标在哪个位置,写操作都是在最后进行追加
f = open("test3.txt", mode="a+", encoding="UTF-8")
f.seek(0)
print(f.read())
f.seek(0)
f.write("bbb")
# seek的应用:比如断点续传
----------二进制操作----------
二进制操作模式有:rb wb ab
r w a 都是基于字符来操作的
rb wb ab b即bytes,和r+ w+ a+操作都一样,但是是通过字节(二进制)来操作的,二进制不需要解码操作,也就是不用加encoding
# rb
f = open("test5", "rb")
print(f.read()) # 输出二进制数据
f.close()
# wb
f = open("test6","wb")
f.write("Hello艾利克斯".encode("utf-8")) # 转换为utf-8字节码数据存入
f.close()
f = open("test7","ab")
f.write("Hello艾利克斯".encode("utf-8")) # 转换为utf-8字节码数据存入
f.close()
----------with的用法----------
# with 利用控制块的方式来操作文件,防止程序中忘记写close()
with open("test7") as f: # 相当于 f = open("test7")
print(f.read())
练习:
# 知识普及: \r\n 表示换行,\r\n有两功能组成,\r是将光标移到开头,\n进行换行
# 字符串拼接: "#" * 3 表示将"#"拼接3次
# 需求:进度条 import sys import time total = 50 for i in range(total + 1): s = "\r%d%% %s" % ((i / total) * 100, "#" * i) sys.stdout.write(s) sys.stdout.flush() time.sleep(0.5)
输出为:
100% ##################################################
练习:
查看haproxy.conf 后端服务器
haproxy.conf文件内容如下:
global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode http timeout connect 5000ms timeout client 50000ms timeout server 50000ms option dontlognull listen stats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog option httpclose option forwardfor log global acl www hdr_reg(host) -i www.oldboy.org use_backend www.oldboy.org if www backend www.oldboy.org server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 backend www.oldboy2.org server 100.1.17.9 100.1.17.9 weight 30 maxconn 3000
程序:
content = input("please input:")
with open("haproxy.conf", encoding="UTF-8") as f:
l = []
flag = False
for line in f:
if line.startswith("backend") and content in line:
flag = True
continue
if line.startswith("backend") and flag:
break
if flag:
l.append(line.strip())
for i in l:
print(i)
运行结果:
please input:www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
练习:文件修改
将“岳飞”插入到第4行
源文件:
hello,我是中国-->1 hello,我是中国-->2 hello,我是中国-->3 hello,我是中国-->4 hello,我是中国-->5
程序:
实现思路:由于文件内容不能直接更改,所以需要通过一个临时文件来进行转换操作
import os
with open("test.txt", encoding="UTF-8") as f1, open("test_tmp.txt", mode="w", encoding="UTF-8") as f2: #同时打开两个文件
count = 0
for line in f1:
if count == 3:
line = "".join([line.strip(), "岳飞\n"])
f2.write(line)
count += 1
os.rename("test.txt", "test.txt.bak") #将test.txt重命名为test.txt.bak
os.rename("test_tmp.txt", "test.txt") #将test_tmp.txt重命名为test.txt
结果:
hello,我是中国-->1
hello,我是中国-->2
hello,我是中国-->3
hello,我是中国-->4岳飞
hello,我是中国-->5

共有 0 条评论