Python之文件处理

一、什么是文件

持久存储信息,操作系统调用。

文件处理流程:

1.应用程序发起打开文件请求,操作系统打开文件;应用程序得到文件句柄赋值给变量

打开文件注意点:

以什么方式存储的,以什么方式读取

2.通过句柄对文件进行操作

3.关闭文件(向操作系统发起关闭命令,操作系统释放文件;如果不关闭文件,只是删除变量,改文件一直会占用操作系统资源)

 

自动关闭文件的操作文件方式:

#文件处理
with open('a.txt','r') as f:
    print(f.read())
print(f.read())
'''zyl
Traceback (most recent call last):

  File "E:/study/python/第二节课/day2/day2/test.py", line 4, in <module>
    print(f.read())
ValueError: I/O operation on closed file.'''

 

二、文件的操作

文件句柄=open('file_name','mode',encoding='utf-8')

1、文件打开方式(mode)

  • r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
  • w,只写模式【不可读;不存在则创建;存在则清空内容】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容】
  • x, 只写模式【不可读;不存在则创建,存在则报错】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码

2.文件写入方式:

#w文本模式的写,文件存在则清空,不存在则创建
f_w=open('a.txt','w',encoding='utf-8')
f_w.write('zyl1\n')
f_w.write('zyl2\n')
f_w.write('zyl3\n')
f_w.close()
#列表的格式写入文件
f=open('a.txt','w',encoding='utf-8')
f.write('3333\n4444\n')
f.writelines(['a\n','b\n','c\n'])  
f.close()
'''3333
4444
a
b
c''' 

3.文件的读取

#以只读的方式打开文件,
f=open('a.txt','r',encoding='utf-8')
print(f.read())
print('second:',f.read())
'''zyl1
zyl2
zyl3
second: '''

#r文本模式的读,在文件不存在,不会创建新文件
f=open('a.txt','r',encoding='utf-8')
print(f.read())
print(f.readable())
print(f.writable())
f.close()
'''zyl1
zyl2

True
False''
#把文件光标移到开始位置,一行一行打印
f.seek(0)
print(f.readline(),end='') #print默认总是换行的,加上end=''可以是打印不换行
print(f.readline())
print(f.readline())
'''zyl1
zyl2

zyl3'''
#把光标移到第二字符处,开始取出所有行打印
f.seek(1)
lines=f.readlines()
print(lines,type(lines))
'''['yl1\n', 'zyl2\n', 'zyl3\n'] <class 'list'>'''

#打印文件变量,关闭文件后在打印文件变量,读取文件内容
print(f)
f.close()
print(f)   #关闭文件后,变量还存在,但是无法读取文件内容,操作系统已经释放资源
f.read()
'''<_io.TextIOWrapper name='a.txt' mode='r' encoding='utf-8'>
<_io.TextIOWrapper name='a.txt' mode='r' encoding='utf-8'>
Traceback (most recent call last):
  File "E:/study/python/第二节课/day2/day2/test.py", line 35, in <module>
    f.read()
ValueError: I/O operation on closed file.'''

文件追加模式打开:

#a文本模式的追加,文件存在光标跳到文件末尾,文件不存在创建
f=open('b.txt','a',encoding='utf-8')
print(f.writable())
print(f.tell())
f.write('3333\n')
f.write('44444\n')
'''True
43'''

 

with的用法:

with open('a.txt','r',encoding='utf-8') as f_r,\
        open('b.txt','w',encoding='utf-8') as f_w:  #打开多个文件,\换行
    for line in f_r:
        if 'zyl' in line:
            line=line.replace('zyl','赵艳玲加油')  #替换后需要赋值
        f_w.write(line)

 b模式读写文件操作

#rb模式即直接从硬盘中读取bytes
f=open('a.txt','rb')
print(f.readline())
'''b'\xe8\xb5\xb5\xe8\x89\xb3\xe7\x8e\xb2123\r\n''''

#wb模式,必须编码后才可写入文件
f=open('a.txt','wb')  #以b方式操作文件时,不可以加编码方式
f.write('你好'.encode('utf-8'))
print(f)
f.close()
print(f)
print(f.read)
'''<_io.BufferedWriter name='a.txt'>
<_io.BufferedWriter name='a.txt'>
<built-in method read of _io.BufferedWriter object at 0x0000000001E81258>'''

#复制图片练习,以b方式打开然后写文件
with open('test.jpg','rb') as f_r,open('cp.jpg','wb') as f_w:
for line in f_r:
f_w.write(line)

文件的其他操作

f.seek()用法,0可以在字符读取模式下使用,1和2必须是在b读模式下使用

def seek(self, *args, **kwargs): # real signature unknown
"""
Change stream position.

Change the stream position to the given byte offset. The offset is
interpreted relative to the position indicated by whence. Values
for whence are:

* 0 -- start of stream (the default); offset should be zero or positive
* 1 -- current stream position; offset may be negative
* 2 -- end of stream; offset is usually negative

Return the new absolute position.
"""
pass

f.tell():

def tell(self, *args, **kwargs): # real signature unknown
""" Return current stream position. """
pass
f=open('a.txt','r',encoding='utf-8')
print(f.read(1))  #只读取一个字符

f=open('a.txt','rb')
print(f.read(6).decode('utf-8'))#读取6个字节,UTF-8是三个字节标示一个汉字

# coding: UTF-8
f=open('a.txt','r',encoding='utf-8')
print(f.read(3))   #读取的三个字符
print(f.tell())    #统计的字节的个数
f.seek(1)          #移动统计的也是字节的个数
print(f.tell())
'''你好赵
9
1'''

#f.seek(offset,0),表示从开头位置算起,偏移offset
f=open('a.txt','rb')
print(f.read(3))   #读取的三个字节,utf-8编码3个字节代表一个汉字
print(f.tell())
f.seek(3,0)
print(f.tell())
print(f.read(3).decode('utf-8'))
'''b'\xe4\xbd\xa0'
3
3
好'''

#f.seek(offset,1),表示从当前位置算起,偏移offset
f=open('a.txt','rb')
print(f.read(3))
print(f.tell())
f.seek(3,1)
print(f.tell())   #打印光标所在位置
print(f.read().decode('utf-8'))
'''b'\xe4\xbd\xa0'
3
6
赵艳玲哈哈哈哈哈哈'''

#f.seek(offset,2),表示从末尾位置算起,偏移offset
f=open('a.txt','rb')
f.seek(0,2)
print(f.tell())
print(f.read())
'''35
b'''''
小程序
import time
import sys
if len(sys.argv)>=3:
    with open(r'%s'%sys.argv[2],'rb') as f:  #r:保持原始输入参数
        f.seek(0,2)
        while True:
            line=f.readline()
            if line:
                print(line)
            else:
                time.sleep(0.2)
else:
    print("请输入正确的文件名称")

 

 
posted @ 2017-07-09 19:01  ling_distance  阅读(214)  评论(0编辑  收藏  举报