Python基本语法_文件操作_读写函数详解

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 目录目录软件环境file文件对象open文件操作读文件read读取所有文件内容readline获取一行内容readlines读取所有文件内容readreadlinereadlines的区别写文件writewritelines写入多行内容...

目录

软件环境

  • 系统
    • UbuntuKylin 14.01
  • 软件
    • Python 2.7.3
    • IPython 4.0.0

file()文件对象

file(name[, mode[, buffering]]) -> file object
Open a file. The mode can be ‘r’, ‘w’ or ‘a’ for reading (default),writing or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. Add a ‘b’ to the mode for binary files.
Add a ‘+’ to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open() function.
Add a ‘U’ to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a ‘\n’ in Python. Also, a file so opened gains the attribute ‘newlines’;the value for this attribute is one of None (no newline read yet), ‘\r’, ‘\n’, ‘\r\n’ or a tuple containing all the newline types seen.
‘U’ cannot be combined with ‘w’ or ‘+’ mode.
file()与open()的功能一致,打开文件或创建文件。都属于内建函数。
file的属性和方法

In [324]: dir(file)
Out[324]: 
['__class__',
 '__delattr__',
 '__doc__',
 '__enter__',
 '__exit__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__iter__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'close',
 'closed',     #标识文件都否已经关闭
 'encoding',   #文件的编码
 'errors',     
 'fileno',     #返回一个Long的文件标签
 'flush',
 'isatty',     #判断文件是否是一个终端设备文件
 'mode',       #打开文件的模式
 'name',       #文件名
 'newlines',   #文件使用的换行符
 'next',       #返回下一行,并将文件指针指向下一行。把一个file用于for循环时,就是调用next()函数来实现遍历。在文件最后执行next()会报错。
 'read',
 'readinto',
 'readline',
 'readlines',
 'seek',
 'softspace',   #boolean型,defalut==0
 'tell',
 'truncate',
 'write',
 'writelines',
 'xreadlines']

open()文件操作

open(…)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
open()函数是file()函数的别名函数,能够打开文件并返回一个文件对象而非文件的内容(应该理解为一个存储着文件的内容的对象,如果想获取内容便需要对文件对象进行操作)。可以指定不同的打开mode(rw),在调用open()函数后一定要调用文件对象内建的close()函数来关闭文件。一般结合try..finally语句来确定会关闭文件对象
注意:当你open()一个文件,实质上是将该文件的内容加载到缓存中,所以当你open()文件之后,对文件做了修改也不会影响到open()返回的对象的value。
常用mode
1. r(read缺省参数):已读的方式打开文件,不能调用write方法,当文件不存在时报错。
2. w(write):已写方式打开文件,能够写入内容并覆盖,不能调用read方法,如果文件不存在,则创建新同名文件。
3. a(append):已追加模式打开文件,可以进行写操作,如果恩健不存在,则创建同名文件。
4. +:使用+允许同时进行读写操作。
5. U:支持所有类型的换行符(\n、\r、\r\n)
6. b:表示对二进制文件进行操作(图片、视频)。
7. t:对文本文件进行操作。
6种mode可以组合使用

读文件

以读方式打开文件后可以调用这三个函数read()\readline()\readlines()
他们都可以传递一个int来指定需要读取的总Size(Bytes)
注意:因为读取的文件会缓存到内存中,所以当需要读取的文件Size大于内存时,需要指定每次读入的Size。

In [15]: !tail /etc/passwd > fileOperation.txt

In [20]: pswd = open('/usr/local/src/pyScript/fileOperation.txt','r')

In [21]: type(pswd)
Out[21]: file

In [32]: pswd
Out[32]: <open file '/usr/local/src/pyScript/fileOperation.txt', mode 'r' at 0x7f048314a420>

read()读取所有文件内容

read(…)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
读取指定Size的内容,缺省参数为全部内容,返回一个String类型对象。

In [34]: content = pswd.read()

In [48]: print content
stack:x:1001:1001::/opt/stack:/bin/bash
memcache:x:116:125:Memcached,,,:/nonexistent:/bin/false
sshd:x:117:65534::/var/run/sshd:/usr/sbin/nologin
postgres:x:118:126:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
rabbitmq:x:119:127:RabbitMQ messaging server,,,:/var/lib/rabbitmq:/bin/false
mysql:x:120:128:MySQL Server,,,:/nonexistent:/bin/false
haproxy:x:121:129::/var/lib/haproxy:/bin/false
libvirt-qemu:x:122:130:Libvirt Qemu,,,:/var/lib/libvirt:/bin/false
libvirt-dnsmasq:x:123:131:Libvirt Dnsmasq,,,:/var/lib/libvirt/dnsmasq:/bin/false
guest-5LawJh:x:124:132:Guest,,,:/tmp/guest-5LawJh:/bin/bash

readline()获取一行内容

readline(…)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
读取文件中的一行含有行结束符的内容,每执行一次会自动获取往下一行的内容,返回一个String。当读取到最后一行再执行此函数时,会返回一个空String,不会报错。

In [62]: pwd = open('fileOperation.txt','r')

In [70]: content = pwd.readline()

In [71]: content
Out[71]: 'stack:x:1001:1001::/opt/stack:/bin/bash\n'

In [72]: content = pwd.readline()

In [73]: content
Out[73]: 'memcache:x:116:125:Memcached,,,:/nonexistent:/bin/false\n'

一个综合例子
open()+fileObject.readline()+try..finally+String.split()+os.path.exists()
因为readline()函数返回的是String类型对象,所以我们可以使用循环来遍历这一行中所有的元素。

import os
def ergodicIndex(fileName):
    pwd = open('fileOperation.txt','r')
    try:
        content  = pwd.readline()
        index = content.split(':')
        for i in index:
            print i,
    finally:
        pwd.close()
if __name__ == '__main__':
    fileName='/usr/local/src/pyScript/fileOperation.txt'
    if os.path.exists(fileName):
        ergodicIndex(fileName)
    else:print "The file not exist"

在处理文件数据中是非常常用的一个方法

In [99]: %run testReadline.py
stack x 1001 1001  /opt/stack /bin/bash

readlines()读取所有文件内容

readlines(…)
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
获取文件所有的内容,并返回一个以每行内容作为一个String元素的List类型对象,本质是通过循环调用readline()实现的。

In [106]: pwd = open('fileOperation.txt','r')

In [108]: content = pwd.readlines()

In [109]: print content
['stack:x:1001:1001::/opt/stack:/bin/bash\n', 'memcache:x:116:125:Memcached,,,:/nonexistent:/bin/false\n', 'sshd:x:117:65534::/var/run/sshd:/usr/sbin/nologin\n', 'postgres:x:118:126:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash\n', 'rabbitmq:x:119:127:RabbitMQ messaging server,,,:/var/lib/rabbitmq:/bin/false\n', 'mysql:x:120:128:MySQL Server,,,:/nonexistent:/bin/false\n', 'haproxy:x:121:129::/var/lib/haproxy:/bin/false\n', 'libvirt-qemu:x:122:130:Libvirt Qemu,,,:/var/lib/libvirt:/bin/false\n', 'libvirt-dnsmasq:x:123:131:Libvirt Dnsmasq,,,:/var/lib/libvirt/dnsmasq:/bin/false\n', 'guest-5LawJh:x:124:132:Guest,,,:/tmp/guest-5LawJh:/bin/bash\n']

In [110]: content[0]
Out[110]: 'stack:x:1001:1001::/opt/stack:/bin/bash\n'

In [111]: content[0][0]
Out[111]: 's'

修改指定行的内容

cfg = open(cfgUrl,'r+')
cfgFile = cfg.readlines()
cfgFile[lineNum] = cfgStr
cfg = open(cfgUrl,'w+')
cfg.writelines(cfgFile)
cfg.flush()   #刷新内存的缓存区,即将缓存区中的内容写入到磁盘,但不会关闭文件。
cfg.close()

将文件以r+的方式打开,并返回一个对象。对对象的内容进行修改后,再将文件以w+的方式打开,将对象的内容写入到文件中。实现对文件指定行的内容修改。

read()、readline()、readlines()的区别

read()和readlines()默认都是获取文件的所有内容。但是read()返回一个String类型对象,元素是一个Char。readlines()返回一个List类型对象,元素是一个Sting。而readline()获取文件的一行内容,返回是一个String。

写文件

注意:调用write()、writeline()时,文件原有的内容会被清空,因为文件指针初始指向文件的首行首个字母,而进行写操作实质就是在文件指针指向的位置开始写入内容。

write()

write(…)
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
将传递的String参数写入并覆盖文件内容,返回None。需要执行close()或flush()后才会将内存的数据写入到文件中。
注意:当你在没有调用close()函数之前,你是可以调用多次write()函数来实现追加额效果,即后来的write()函数的写入的内容并不会覆盖前一次使用write()函数写入的内容,但是不会自动添加换行符。

In [153]: pwd = open('fileOperation.txt','w')

In [155]: pwd.write('My name is JMilk')

In [157]: pwd.flush()

In [159]: pwd.write('My name is chocolate')

In [161]: pwd.flush()

In [163]: pwd.write('123')

In [165]: pwd.write('456')

In [167]: pwd.close()

结果:

My name is JMilkMy name is chocolate123456

一个综合例子
open()+fileObject.write()+os.path.exists()+ergodicDictionary

import os
def write_test(fileName,content_iterable):
    try:
        pwd = open(fileName,'w')
        for key,value in content_iterable.items():
            pwd.write(key+'\t'+value+'\n')  #传入String类型参数同时加入换行符
    finally:
        pwd.close()

if __name__ == '__main__':
    fileName = '/usr/local/src/pyScript/fileOperation.txt'
    dic = {'name':'Jmilk','age':'23','city':'BJ'}
    if os.path.exists(fileName):
        write_test(fileName,dic)
    else:print 'File not exist!'

结果:

city    BJ
age     23
name    Jmilk

writelines()写入多行内容

writelines(…)
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
将传递的迭代对象的String元素逐个写入文件,相当于没一行都调用额write()函数,但是不会自动添加换行符。
修改上面的综合例子

import os
def write_lines(fileName,content_iterable):
    try:
        pwd = open(fileName,'w')
        pwd.writelines(content_iterable) #传递List类型参数
    finally:
        pwd.close()

if __name__ == '__main__':
    fileName = '/usr/local/src/pyScript/fileOperation.txt'
    li = ['my name is Jmilk'+'\n','My name is chocolate'+'\n']  #定义List时加入换行符
    if os.path.exists(fileName):
        write_lines(fileName,li)
    else:print 'File not exist!'

结果:

my name is Jmilk
My name is chocolate

write()和writelines()的区别

从上面两个例子中可以看出,write()接受的是String类型参数,所以可以在()中对实参进行修改加入’\n’。而writelines()接受的是iterable类型参数,并且iteraber对象的元素需要为String类型,只能在定义iterable的时候加入’\n’。在写入多行内容时writelines()会比write()更有效率。再一次反映 数据结构决定了对象操作这一句话,所以对数据结构的理解是非常重要的。Python数据结构,请参考:http://blog.csdn.net/jmilk/article/details/48391283

将标准输出重定向写入到指定文件

系统标准输入、输出、Err本质是一个类文件对象。重定向即:
sys.stdout = fileObject_write
Example

In [59]: pycat stdoTest.py
#!/usr/bin/env python
#Filename:stdoTest.py
#coding=utf8
import sys


fristOut = sys.stdout  #备份初始的输出文件对象
print type(fristOut)

logOut = open('/usr/local/src/pyScript/out.log','w') 
sys.stdout = logOut  #重定向输出到新的文件对象
print 'Test stdout.'  #重定向后,不会打印到屏幕

logOut.close()   #关闭open()打开的文件对象
sys.stdout = fristOut  #还原输出文件对象

In [60]: run stdoTest.py
<type 'file'>

In [61]: cat out.log
Test stdout.

文件指针

文件指针:当使用open()函数打开一个文件并返回一个文件对象后,在文件对象中会存放着当前”光标”在文件中的位置,对文件进行的读、写、截断操作都是基于文件指针,并从文件指针+1开始进行的操作。。这个位置称为文件指针(从文件头部开始计算的字节数),与C语言额指针概念相似,实质是文件中位置的标识。大部分的文件操作都是基于文件指针来实现的。

tell()获取当前文件指针(位置)

tell(…)
tell() -> current file position, an integer (may be a long integer).

In [283]: pwd = open('fileOperation.txt','rw+')

In [285]: pwd.tell()
Out[285]: 0

truncate()截断文件

truncate(…)
truncate([size]) -> None. Truncate the file to at most size bytes.
Size defaults to the current file position, as returned by tell().
默认从文件指针指向的位置开始截断文件内容,也可以通过传递int参数n来指定截断的起始位置,即改变文件指针的位置。从文件指针指向的位置n开始,之后的文件内容(不包含n)全部删除,以可修改mode打开的文件可以使用此方法

In [273]: cat fileOperation.txt
0123456789

In [274]: pwd = open('fileOperation.txt','rw+')

In [275]: pwd.truncate(5)

In [276]: pwd.close()

In [277]: cat fileOperation.txt
01234

seek()转移文件指针

seek(…)
seek(offset[, whence]) -> None. Move to new file position.
可以接收偏移量和选项作为参数,返回None。
当whence==0时,将文件指针从文件头部转移到”偏移量”指定的字符处。
当whence==1时,将文件指针从文件的当前位置往后转移”偏移量”指定的字符数。
当whence==2时,将文件指针从文件尾部向前移动”偏移量”指定的字符数。
一个综合例子
truncate()+tell()+seek()

In [308]: %cat fileOperation.txt
0123456789

In [309]: pwd = open('fileOperation.txt','rw+')

In [310]: pwd.tell()
Out[310]: 0

In [311]: pwd.seek(5)

In [312]: pwd.tell()
Out[312]: 5

In [313]: pwd.truncate()

In [314]: pwd.close()

In [315]: %cat fileOperation.txt
01234

总结:上面的例子可以看见,可以通过seek()函数来移动文件指针,并结合truncate()来截断文件指针指定位置后面的文件内容。同理,当传递int参数给truncate(n)后也会改变文件指针。
注意:当对文件进行了读、写操作后都会改变文件指针的值,而改变的值相当于操作过的len(String)。

最后

最近一直在写powershell,但是也没有整理出比较模块化的笔记,估计powershell主题还需要等待一段时间了。:(

Jmilk

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
1月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
158 1
|
1月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
243 1
|
1月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
137 0
|
2月前
|
数据可视化 Linux iOS开发
Python脚本转EXE文件实战指南:从原理到操作全解析
本教程详解如何将Python脚本打包为EXE文件,涵盖PyInstaller、auto-py-to-exe和cx_Freeze三种工具,包含实战案例与常见问题解决方案,助你轻松发布独立运行的Python程序。
920 2
|
2月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
264 101
|
2月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
202 99
|
2月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
184 98
|
2月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
3月前
|
Python
Python 函数定义
Python 函数定义
463 155
|
1月前
|
监控 机器人 编译器
如何将python代码打包成exe文件---PyInstaller打包之神
PyInstaller可将Python程序打包为独立可执行文件,无需用户安装Python环境。它自动分析代码依赖,整合解释器、库及资源,支持一键生成exe,方便分发。使用pip安装后,通过简单命令即可完成打包,适合各类项目部署。

推荐镜像

更多