python文件操作步骤
#第一步:调用文件
f=open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')
#第二部:使用文件
print(f.readlines())
#第三部:关闭文件
f.close()
#python中内置函数with可以自动关闭文件:
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
print(f.readlines())
三种调用文件的路径的写法
open(r'D:\untitled\venv\Include\blacklist.txt') #r --read 只读,代表' '内的字符串没有其他含义不进行转义
open('D:\\untitled\\venv\\Include\\blacklist.txt')
open('D:/untitled/venv/Include/blacklist.txt')
读(rt)
read读取全部内容
f.read(int)可指定参数int, ‘rt’ --->参数int代表读取int个字符 'rb'--->参数int代表读取int个字节
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
print(f.read())
...运行结果
艾妮
你好
hello
world
readline按行读取
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
print(f.readline(2))
...运行结果
艾妮
readlines把内容以列表形式展现
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='gbk')as f:
print(f.readlines())
...运行结果
['艾妮\n', '你好\n', 'hello\n', 'world\n']
覆盖写(wt)
with open(r'D:\untitled\venv\Include\blacklist.txt', 'w', encoding='utf-8')as f:
f.write('你好不好')
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
print(f.readlines())
...运行结果
['你好不好']
追加写appand(at)
with open(r'D:\untitled\venv\Include\blacklist.txt', 'a', encoding='utf-8')as f:
f.write('艾妮'+'\n')
with open(r'D:\untitled\venv\Include\blacklist.txt', 'r', encoding='utf-8')as f:
print(f.read())
...运行结果
你好不好
艾妮
艾妮
艾妮
(rb,wb,ab)
rb:read bytes 二进制字节方式读取
wb:write bytes 二进制字节方式覆盖写
ab:appand bytes 二进制字节方式追加写
示例:
with open(r'D:\untitled\venv\Include\blacklist.txt', 'wb')as f:
f.write('艾妮'.encode('utf-8'))
with open(r'D:\untitled\venv\Include\blacklist.txt', 'ab')as f:
f.write('艾妮'.encode('utf-8'))
with open(r'D:\untitled\venv\Include\blacklist.txt', 'rb')as f:
print(f.read())
f.seek(0,0) #把光标移动到开头
print(f.read().decode('utf-8'))
...运行结果
b'\xe8\x89\xbe\xe5\xa6\xae\xe8\x89\xbe\xe5\xa6\xae'
艾妮艾妮
文件的光标移动
f.seek(0,0) 后面的0代表把光标移动到开头
f.seek(0,1) 后面的1代表相对位置
f.seek(0,2) 后面的2代表把光标移动到末尾
示例:# tail -f message | grep '404'
import time
with open(r'C:\Users\Administrator.USER-20190512NQ\Desktop\a.txt', 'rb') as f:
f.seek(0, 2)
while True:
data = f.read()
if b'404' in data:
print(data.decode('utf-8'))
else:
time.sleep(0.2)