博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 文件处理
阅读量:4550 次
发布时间:2019-06-08

本文共 4872 字,大约阅读时间需要 16 分钟。

目录

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

打开文件

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)   #指针位置调为0a = 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"

文件对象方法:

1、-FileObject.close()

2、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()

3、readlines

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

4、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)) #数字指的是读的是字符

5、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 "
", line 1, in
StopIteration

6、write

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

7、writelines

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

8、FileObjectseek (偏移量,选项)

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

9、-FileObject.flush

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

10、find查找

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

11、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)

12、truncate截断

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

Python的文件类型

1、源代码

Python源代码的文件已“py”为扩展名,由Python程序解释,不需要编译;用./1.py时 需要写Python的路径#!/usr/bin/python,然后chmod赋予权限

2、字节代码

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

3、优化代码

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

tail -f access.log

import timewith 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 oswith 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')  #改名

转载于:https://www.cnblogs.com/ma-ke/p/6925430.html

你可能感兴趣的文章
比较:I/O成员函数getline() 与 get()(第二种用法)的用法异同
查看>>
201671010118 2016-2017-2《Java程序设计》 第十一周学习心得
查看>>
Get Sauce(状压DP)
查看>>
Office2007 升级到 office2010
查看>>
SpringBoot整合Hibernate
查看>>
PPT1 例2
查看>>
extern外部方法使用C#简单例子
查看>>
血液循环结构
查看>>
SQL Server统计数据库中表个数、视图个数、存储过程个数
查看>>
设计模式:观察者模式
查看>>
JVM体系结构之六:堆Heap之1
查看>>
TCP之二:TCP的三次握手与四次分手
查看>>
es的返回数据结构
查看>>
[ActionScript 3.0] as3处理xml的功能和遍历节点
查看>>
linux学习(6)-redhat安装xwindow环境
查看>>
6.28 加法作业
查看>>
CentOS6+nginx+uwsgi+mysql+django1.6.6+python2.6.6
查看>>
【bzoj2829】信用卡凸包 凸包
查看>>
oracle 游标
查看>>
关于拍照那些小事——五一苏行记(三)
查看>>