1,文件操作。 文件000.py
1,文件路径:'D:\workplace\work\python_Demo\文件.py'
2,编码方式:utf-8 gbk 。。。。
3,操作方式:只读,只写,追加,读写,写读.....
4.以什么编码方式储存的文件,就以什么编码打开进行操作。
with open('D:\workplace\work\python_Demo\\222.py','r',encoding='utf-8') as f:
f.seek(12) #按照字节的位置定光标
print(f.tell()) #查找光标的位置
content = f.read() #读出来的都是字符
content.strip()
print(content)
f.close()
# #最常用的r+ 模式下先写后读的话,从开头写多少占多少位,会替换,先读后写的话,会在末尾加上
with open('D:\workplace\work\python_Demo\\222.py','r+',encoding='utf-8') as f:
f.read()
f.write('@@@')
f.close()
with open('D:\workplace\work\python_Demo\\222.py','r+',encoding='utf-8') as f:
f.write('$$$$$') #从开头写多少占多少位,会替换
f.close()
f = open('222.py','a+',encoding='utf-8')
f.write('HASDF')
postion = f.tell()
f.seek(postion-3) #光标移动到后三位,再读取
print(f.read(2)) #读取光标后的两位
print(f.readline()) # 一行一行的读
print(f.readlines()) # 每一行当成列表中的一个元素,添加到list中
f.truncate(5) #截取前五个,后面的清空
#文件的复制
#打开文件
file_read= open('文件1')
file_write = open('文件1复件','w')
#读,写文件
content = file_read.read()
file_write.write(content)
#关闭
file_read.close()
file_write.close()
#复制大文件
#打开文件
file_read= open('文件1')
file_write = open('文件2复件','w')
#读,写文件
while True:
#读取一行内容
content = file_read.readline()
if not content:
break
file_write.write(content)
#关闭
file_read.close()
file_write.close()
#
# 1.处理文件,用户指定要查找的文件和内容,将文件中包含要查找内容的每一行都输出到屏幕
def check_file(filename,aim):
with open(filename,encoding='utf-8') as f: #句柄 : handler,文件操作符,文件句柄
for i in f:
if aim in i:
yield i
g = check_file('文件000.py','django')
for i in g:
print(i.strip())
print("=========")
#在每行的开头添加
with open("文件000.py",encoding='utf-8') as f0:
for i in f0:
if 'django' in i:
print("====="+i)
# #替换 r+模式下先写后读的话,从开头写多少占多少位,会替换,先读后写的话,会在末尾加上
with open("文件000.py",'r+',encoding='utf-8') as f0:
for i in f0:
if 'django' in i:
line = i.replace('django','aaaaaaaaaa')
print(line)
f0.write(line)
f0.close()