python 文件处理

复制到有道云打开会产生目录vim

打开文件

python进行文件读写的函数open或file函数

使用open打开文件:

默认使用平台编码
>>> fo = open('/tmp/make/ab.txt',encoding='utf-8') #打开文件
>>> fo.read() #使用read读取数据
>>> fo.close() #关闭

file打开文件(限python2中)

>>> f1 = file('/tmp/make/ab.txt')
>>> f1.read()
>>> f1.close()
>>> f1.read() #关闭以后再读取时读取不到的

上下文管理

with open('a.text','r',encoding='utf-8') as f,open('b.text','r',encoding='utf-8') as b_f:
    print(f.read())
    print(b_f.read())

文件操做

r只读:

f = open('test.log','r',encoding='utf-8')
a = f.read()
print(a)

w 写(有文件则先清空再写,没有则建立再写)

写入,先删除原文件,在从新写入,若是我那件没有则建立
f = open('test.log','w',encoding='utf-8')
a = f.write('car.\n索宁')
print(a)    #返回字符

a 追加(指针会先移动到最后)

f = open('test.log','a',encoding='utf-8')
a = f.write('girl\n索宁')
print(a)    #返回字符

读写 r+

f = open('test.log','r+',encoding='utf-8')
a = f.read()
print(a)
f.write('nick')

写读 w+(会先清空!!!)

写读,先删除原文件,在从新写入,若是文件没有则建立(能够写入输出)
f = open('test.log','w+',encoding='utf-8')
a = f.read()
print(a)
f.write('jenny')

写读 a+(指针先移到最后)

f = open('test.log','a+',encoding='utf-8')
f.seek(0)   #指针位置调为0
a = f.read()
print(a)
b = f.write('nick')
print(b)

rb

f = open('test.log','rb')
a = f.read()
print(str(a,decode='utf-8')) #须要解码

f=open('sb.jpg','r',encoding='utf-8') #文本的方式读不了二进制文件
print(f.read())

with open('sb.jpg','rb') as read_f,\
        open('sb_alex.jpg','wb') as write_f:
    data=read_f.read()
     write_f.write(data)

ab

f = open('test.log','ab')
f.write(bytes('索宁\ncar',encoding='utf-8'))
f.write(b'jenny')

关闭文件

f.close()

内存刷到硬盘

f.flush()

获取指针位置

f.tell()

指定文件中指针位置

f.seek(0)

读取所有内容(若是设置了size,就读取size字节)

f.read()
f.read(9)

读取一行

f.readline()

读到的每一行内容做为列表的一个元素

f.readlines()

U :支持全部换行符号。“”,"\n"."\r\n"优化

文件对象方法:

一、-FileObject.close()

二、readline

格式:String=FileObject.readline([size])
说明:每次读取文件的一行
size:是指每行每次读取size个字节,知道行的末尾
例:
>>> f1 = open('test.txt') #打开文件
>>> f1.readline() #每次读取一行
'hello\n'
>>> f1.readline()
"what's\n"
>>> f1.readline()
'your\n'
>>> f1.readline()
'name\n'
>>> f1.readline() #超出以后readline会读取空字符串
>>>..
>>> f1,close()

三、readlines

格式:List=FileObject.readlines([size])
说明:多行读,返回一个列表 (读取全部而后以列表的形式保存下来)
size:每行读入size字符,而后继续按size读,而不是每次读入行的四则个字符
例:
>>> f1=open('test.txt')
>>> f1.readlines()
['hello\n', "what's\n", 'your\n', 'name\n']

四、read

with open('a.txt','r',encoding='utf-8') as f:
    print(f.read(4)) #数字指的是读的是字符

with open('a.txt','rb') as f:
    print(f.read(1)) #数字指的是读的是字符

五、next

格式:-FileObject.next()
例:
>>> f1 = open('test.txt')
>>> f1.next()
'hello\n'
>>> f1.next()
"what's\n"
>>> f1.next()
'your\n'
>>> f1.next()
'name\n'
>>> f1.next() #跟readline不一样的是next超出以后会中止迭代,给出警示
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

六、write

格式:FileObject.write(string)
说明:write和后面的weitelines在写入前会是否清楚文件中原来的s数据,
再从新写入新的内容,取决于打开文件的模式。

七、writelines

格式:FileObject.writelines(list)
说明:多行写
效率比write高,速度更快,少许写入可使用write

八、FileObjectseek (偏移量,选项)

选项=0时,表示将文件指针指向从文件头部到“偏移量”字节处。
选项=1时,表示文件指针指向从文件的当前位置,向后移动“偏移量”字节
选项=2时,表示将文件指针指向从文件的尾部向前移动“偏移量”字节。

九、-FileObject.flush

提交更新
例:
>>> f1 = open('test.txt','a')
>>> l = ['one\n','two\n','three\n']
>>> f1.writelines(l)
>>> f1.flush() #flush实现文件数据的提交
>>> f1.close()

十、find查找

>>> msg = "what's your company's name?"
>>> msg
"what's your company's name?"
>>> msg.find('name')
22
>>> msg.find('company')
12

十一、seek(指定光标位置)

with open('a.txt','r',encoding='utf-8') as f:
    f.seek(3) #seek内指定的数字表明字节(指定光标位置)
    print(f.tell()) #当前光标所在的位置
    print(f.read())
    
with open('b.txt','rb') as f:
    f.read()
    f.seek(3) #默认状况,是以文件起始位置做为开始,日后移动3个bytes
    f.read(1)
    print(f.tell())
    f.seek(2,1) #1 表明以当前光标所在的位置为开始,日后移动2个 bytes
    print(f.tell())

    f.seek(-1,2) #2表以当前光标所在的位置为开始,日后移动2个 bytes
    print(f.tell())

    f.seek(0,2)

十二、truncate截断

with open('a.txt','r+',encoding='utf-8') as f:
    #f.seek(3) #seek内指定的数字表明字节
    print(f.read())

    f.truncate(3)

Python的文件类型

一、源代码

Python源代码的文件已“py”为扩展名,由Python程序解释,不须要编译;

用./1.py时 须要写Python的路径#!/usr/bin/python,而后chmod赋予权限

二、字节代码

Python源文件经编译后生成的扩展名为“pyc”的文件;
编译方法 import py_compile
py_compile.compile("hello.py") #hello py为上分文件
例:vim 1.py
#!/usr/bin/python
print 'hello'
$chmod +x 1.py
$vim 2.py
import py_compile
py_compile.compile("1.py")
$python 2.py
$ls
1.py 1.pyc 2.py

三、优化代码

通过优化的原文件,扩展名为“.pyo”
python -O -m py_commpile hello.py
例:$python -O -m py_commpile 1.py
$ls
1.py 1.pyc 1.pyo
$chmod +x *
python 1.py python 1.pyc python 1.pyo #这三种的执行结果同样,但python1.py最经常使用
能够简明的了解那里有错误

tail -f access.log

import time
with open('access.log','r',encoding='utf-8') as f:
    f.seek(0,2)
    while True:
        line=f.readline().strip()
        if line:
            print('新增一行日志',line)
        time.sleep(0.5)

文件复制、修改

复制:

打开一个a文件,用readline读取到b文件
with open('a.txt','r') as a_f,open('b.txt','w') as b_f:
    for line in a_f.readlines():
        b_f.write(line)

修改:

import os
with open('a.txt','r') as a_f,open('b.txt','w') as b_f:
    for line in a_f.readlines():
        if line.startswith('111'):
            line='222333\n'
    b_f.write(line)

os.remove('a.txt')
os.rename('b.txt','a.txt')  #更名
相关文章
相关标签/搜索