文件操作基础



文件操作流程:
1 打开文件 open
2操作文件 read write
3关闭文件 close
文件 可迭代对象

# -----------------r 只读
f = open('test1',encoding = 'utf8') #cpu调用内核态 操作系统将test1放入内存
data = f.read(5) #返回文件内容,调用方法读取文件 #读指定个数的字符
print(data)
data1 = f.readline() # 读取单行内容
data2 =f.readlines() # 以列表形式返回多行
print(data2)

#只是显示的文件修改了 ,磁盘上的文件没有被修改
count = 0
for line in f.readlines(): # 将文件全部读到内存中
if count == 3:
line = ''.join([line.strip(),'岳飞'])
print(line.strip())
count += 1

for line in f: #优化内存 将文件一行一行的读到内存中
if count == 3:
line = ''.join([line.strip(),'岳飞'])
print(line.strip())
count += 1

# -------------------w 覆盖写
f = open('test1',mode = 'w',encoding = 'utf8')
#print(f.read()) #不可读 启用w模式之前删除之前有的内容
f.write('yyyyyyyyyy kkkkkk')
f.flush()# 刷新 将写入内存中的内容立即写到磁盘上
# 光标移到第一位 光标移到下一行
# stdout 标准输出
# 进度条
import sys,time
for i in range(100):
s = ' %d%% %s'%(i,'#'*i)
sys.stdout.write(s) # 以覆盖的形式输出s
#sys.stdout.flush()
time.sleep(0.3)
# ----------------------------------------------可读可写的3种模式:
# -------------------------r+ 默认光标 在开始位置 追加写
f = open('test1',mode = 'r+',encoding = 'utf8')
print(f.read())
print(f.write('yyyyyyyyyyyyyyyyy'))
print(f.write('yyyyyyyyyyyyyyyyy'))
f.flush()
f.seek(0)
print(f.read())

#----------------------------w+ 覆盖写, 读取内容用seek调整
f = open('test1',mode = 'w+',encoding = 'utf8')
print(f.write('xxxxxxxxx中国'))
print(f.read()) #读不到
f.seek(0)
print(f.read())
f.seek(-2,2) # 报错 因为 seek以字节的方式移动光标,需要改变文件打开方式为wb+
print(f.read())
#----------------------------a+ 光标默认在文件最后的位置,并且不管光标在哪里,一定是追加写,因为磁盘写上的内容不可变
# 想读取内容用seek调整
f = open('test1','a+',encoding = 'utf8')
print(f.read()) # 读不到
print(f.write('yyyyyyyyyyyyyyyyyy'))
print(f.read()) # 读不到
f.seek(5)
print(f.read()) # 读到第5个字节之后的内容
#--------------------------------------------------以字节的形式读写文件的3种方式
#-----------------------------rb+
f = open('test1','rb+')
print(f.read())
f.write('cccccccccccccccc'.encode('gbk'))#必须将写入的unicode编码成为字节形式的数据

#-----------------------------wb+
f = open('test1','wb+')
f.write('aaaaaaaaaaaaaaaaaaa'.encode('gbk'))
print(f.read())
#------------------------------ab+
f = open('test1','ab+')
f.write('bbbbbbbbbbbbbbbbbbbbbbb'.encode('utf8'))
f.seek(8)
print(f.read())
#修改磁盘上的文件: 将文件读出之后修改,再放入一个新的可写文件,最后修改文件名称
with open('test1',encoding = 'utf8')as f_read,open('test2','w',encoding = 'utf8')as f_write:
count = 0
for line in f_read:
if count == 3:
line = ''.join([line.strip(),'岳飞 '])
f_write.write(line)
count += 1
import os # 修改文件名称,将新建的文件命名为原文件
os.rename('test1','test_bak')
os.rename('test2','test1')

#查找一个文件中特定的一个字符串 标志位
while 3:
m = input('please input your url:')
l = []
flag = False
with open('haproxy.conf',encoding = 'utf8')as f_read:
for line in f_read:
if line.startswith('backend') and m in line:
flag = True
continue
if line.startswith('backend') and flag:
flag = False

if flag:
l.append(line.strip())


for i in l:
print(i)
#调整光标位置的两个命令
seek
1. 作用:用于移动文件读写指针到指定的位置
   注:以字节的方式移动光标,所以要以字节的方式打开文件

2. 语法格式:file.seek(offset, whence=0):

--> offset: 偏移量,需要向前或者是向后移动的字节数,-1向前移动1个字节,1向后移动1个字节
--> whence: 可选值,默认为0, 可选值为1或者2,表示从何处开始计算偏移,具体来说,

--> 0表示从当前位置开始计算偏移
--> 1表示从文件头位置开始计算偏移
--> 2表示从文件尾开始计算偏移

 1 >>> x = file('my.log', 'r')    #读取一个文件  
 2 >>> x.tell()           #获得当前文件读取指针  
 3 0L              #当前文件指针在文件头处  
 4 >>> x.seek(3)          #将文件指针向前移动3个字节  
 5 >>> x.tell()  
 6 3L              #指针已经移动到了第3个字节处  
 7 >>> x.seek(5,1)            #表示从文件头处开始移动指针,向前移动5个字节  
 8 >>> x.tell()                 
 9 5L              #当前文件读取指针已经移动到第5个字节处  
10 >>> x.seek(0,0)            #表示将文件指针移动到文件头处  
11 >>> x.tell()  
12 0L  
13 >>> x.seek(0,2)            #表示将文件读取指针移动到文件尾部  
14 >>> x.tell()                 
15 214L                #可以得到文件大小为214B  
16 >>> x.seek(-2,2)       #表示从文件尾部开始移动指针,向前移动2个字节  
17 >>> x.tell()  
View Code
tell
1. 作用:获取当前文件读取指针的位置

2. 语法格式: file.tell() 注: 此方法没有参数(以字节记)

#flush命令
用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。一般情况下,文件关闭后会自动刷新缓冲区,
但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
flush的语法:
fileObject.flush();

#文件标准输出stdout

sys.stdout 与 print

当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+' ')

print 将你需要的内容打印到了控制台,然后追加了一个换行符

print 会调用 sys.stdout 的 write 方法

以下两行在事实上等价:

sys.stdout.write('hello'+'
')
print 'hello'

sys.stdin 与 raw_input

当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入

以下两组在事实上等价:

hi=raw_input('hello? ')

print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the '
' in input stream

应用:进度条

1 import sys
2 for i in range(100):
3     s = '
%d%% %s'%(i,'#'*i)    
4     sys.stdout.write(s)           
5     sys.stdout.flush()
6     import time
7     time.sleep(0.5)









原文地址:https://www.cnblogs.com/liuguniang/p/6681482.html