先看看官方说明:

The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

As mentioned in the Overview, Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.
In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

r、w、a 为打开文件的基本模式,分别对应只读、只写、追加模式。

b、t、+ 与以上的文件打开模式组合使用,分别对应二进制模式,文本模式,读写模式。

整理一下:

———————————————————————————————————————————————————————————————————————————————————————
mode | 描述
———————————————————————————————————————————————————————————————————————————————————————
r | 以只读方式打开文件(默认),如果文件不存在,则抛出FileNotFoundError异常
———————————————————————————————————————————————————————————————————————————————————————
w | 以只写方式打开文件。指针在开头,文件不存在时创建,文件存在时,则清空再写入新内容。
———————————————————————————————————————————————————————————————————————————————————————
a | 以追加只写方式打开文件,指针移到文件末尾。文件不存在时创建。
———————————————————————————————————————————————————————————————————————————————————————
x | 以追加方式打开文件,文件不存在时创建,文件存在时抛出FileExistsError异常。
———————————————————————————————————————————————————————————————————————————————————————
r+ | 读写,指针在开头,可以写到文件任何位置
———————————————————————————————————————————————————————————————————————————————————————
w+ | 读写,清空文件内容
———————————————————————————————————————————————————————————————————————————————————————
a+ | 读写,追加,只能写在文件末尾
———————————————————————————————————————————————————————————————————————————————————————

打开文件

f = open('path','mode')

将内存数据写入文件

f.flush()

关闭文件

f.close()

创建一个文件

# vim users.txt
keith1:18:110
keith2:19:111
keith3:20:112
keith4:21:113

查看帮助文档

>>> f=open('users.txt')
>>> type(f)
<class '_io.TextIOWrapper'> >>> help(open)
>>> help(f) >>> dir(f)
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']

在对文件进行操作后,一定要牢记一件事情:file.close()。

如果不关闭,它还驻留在内存中,后面又没有对它的操作,既浪费内存空间,也增加了文件的安全风险。

有另一种方法能够不用手动close()文件,那就是使用with的方式打开文件。

>>> with open('users.txt') as f:
... print(f.read())
...
keith1:18:110
keith2:19:111
keith3:20:112
keith4:21:113

读文件

f.read(size)         读取文件size个字节内容,返回字符串。如果不指定size,则读取全部内容。
f.readline(size) 读取文件一行size个字节,返回字符串。如果不指定size,则显示一整行。
f.readlines(hint) 读取文件所有行,返回列表。如果hint小于一行的字符数则读取一行,如果hint大于一行小于两行字符数则读取两行,以此类推。
>>> help(f.read)
Help on built-in function read: read(size=-1, /) method of _io.TextIOWrapper instance
Read at most n characters from stream. Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.
>>> help(f.readline)
Help on built-in function readline: readline(size=-1, /) method of _io.TextIOWrapper instance
Read until newline or EOF. Returns an empty string if EOF is hit immediately.
>>> help(f.readlines)
Help on built-in function readlines: readlines(hint=-1, /) method of _io.TextIOWrapper instance
Return a list of lines from the stream. hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
>>> f.read()
'keith1:18:110\nkeith2:19:111\nkeith3:20:112\nkeith4:21:113' >>> f.readline()
'keith1:18:110\n' >>> f.readlines()
['keith1:18:110\n', 'keith2:19:111\n', 'keith3:20:112\n', 'keith4:21:113']

在python中,'\n'表示换行,这也是unix系统中的规范。但是在windows系统中,用'\r\n'表示换行。不过还好,python在处理的时候,会自动将'\r\n'转换为'\n'。

遍历文件

>>> f=open('users.txt')
>>> for line in f:
... print(line, end='')
...
keith1:18:110
keith2:19:111
keith3:20:112
keith4:21:113

for循环是一行一行地读取文件内容,每次扫描一行,遇到结束符号\n表示本行结束。

文件指针

指针就是文件操作的位置。

获取指针当前位置

>>> help(f.tell)
Help on built-in function tell: tell() method of _io.TextIOWrapper instance
Return current stream position.

移动指针

>>> help(f.seek)
Help on built-in function seek: seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
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 默认为起始位置,偏移量为0或者正数。
* 1 -- current stream position; offset may be negative 当前位置,偏移量可以是负数。
* 2 -- end of stream; offset is usually negative 结束位置,偏移量通常是负数。 Return the new absolute position.

cookie表示相对whence的偏移量。

whence表示从何处开始。

>>> f=open('users.txt')
>>> f.tell()
0
>>> f.read(2)
'ke'
>>> f.tell()
2
>>> f.read(3)
'ith'
>>> f.tell()
5
>>> f.seek(0)
0
>>> f.tell()
0

需要注意的是,seek移动指针之前默认先会调用flush。

参考:

https://docs.python.org/3/library/functions.html#open

https://docs.python.org/3/library/io.html#io.TextIOBase.seek

http://www.runoob.com/python/file-seek.html

https://docs.python.org/3/library/io.html#io.IOBase.writelines

文件操作,内置函数open()的更多相关文章

  1. [转]python file文件操作--内置对象open

    python file文件操作--内置对象open   说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前 ...

  2. python file文件操作--内置对象open

    说明: 1. 函数功能打开一个文件,返回一个文件读写对象,然后可以对文件进行相应读写操作. 2. file参数表示的需要打开文件的相对路径(当前工作目录)或者一个绝对路径,当传入路径不存在此文件会报错 ...

  3. 「Python」字符串操作内置函数

    目录: capitalize casefold center count encode decode endswith expandtabs find format format_map index ...

  4. 使用R内置函数操作数据框

    我们已经学习了数据框的基础,这里回顾一下用于筛选数据框的内置函数.尽管数据框本质上是一个由向量构成的列表,由于各列长度相同,所以可以将其看作矩阵进行访问和操作.选择满足特定条件的行,需要为 [ ] 的 ...

  5. 【原创】Matlab.NET混合编程技巧之找出Matlab内置函数

                  本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新    Matlab和C#混合编程文章目录 :[目录]Matlab和C#混合编程文章目录 Matlab与.N ...

  6. Matlab.NET混编技巧之——找出Matlab内置函数

    原文 http://www.cnblogs.com/asxinyu/p/3295309.html Matlab与.NET的混合编程,掌握了基本过程,加上一定的开发经验和算法基础,肯 定不难.反之,有时 ...

  7. Matlab.NET混合编程技巧之——找出Matlab内置函数

    原文:[原创]Matlab.NET混合编程技巧之--找出Matlab内置函数 Matlab与.NET的混合编程,掌握了基本过程,加上一定的开发经验和算法基础,肯定不难.反之,有时候一个小错误,可能抓破 ...

  8. Matlab内置函数

    [原创]Matlab.NET混编技巧之——找出Matlab内置函数   Matlab与.NET的混合编程,掌握了基本过程,加上一定的开发经验和算法基础,肯定不难.反之,有时候一个小错误,可能抓破脑袋, ...

  9. python语法基础-函数-内置函数和匿名函数-长期维护

    ##################     内置函数        #######################  """ 一共是 68个内置函数: 反射相关的内置函 ...

  10. set、def、lambda、内置函数、文件操作

    set : 无序,不重复,可以嵌套 .add (添加元素) .update(接收可迭代对象)---等于批量 添加 .diffrents()两个集合不同差 .sysmmetric difference( ...

随机推荐

  1. vue中的img src 动态加载本地json的图片路径写法。

    目录: 注意:本地json文件和json文件里的图片地址都必须写在static 静态文件夹里:否则json文件里的url地址找不到. major_info.json文件里的图片路径写法 页面通过v-b ...

  2. Python实现随机读取文本N行数据

    工作中需要判断某个文本中的URL是否能正常访问,并且随机获取其中N行能正常访问的URL数据,我的思路是:读取文本每一行数据,用urlopen访问,将返回状态码为200的URL保存到一个列表,获得列表长 ...

  3. POJ1159

    这竟然是IOI虽然是2000年的,但其实也改变不了它水题的本质 我写了两种方法,这里都讲一下吧 考虑记忆化搜索,用f[i][j]表示当区间的左端为i,右端为j时最少要添加多少字符,所以ans就为f[1 ...

  4. 洛咕 P2336 [SCOI2012]喵星球上的点名

    洛咕 P2336 [SCOI2012]喵星球上的点名 先求出SA和height,一个点名串对应的就是一段区间,还有很多个点,就转化成了 有很多个区间,很多个点集,对每个区间计算和多少个点集有交,对每个 ...

  5. JVM技术周报第1期

    JVM技术周报 · 第1期 JVM技术每周分享整理了JVM技术交流群每周讨论的内容,由群内成员整理归纳而成.如果你有兴趣入群讨论,请关注「Java技术精选」公众号,通过右下角菜单「入群交流」加我好友, ...

  6. (转载)利用SIFT和RANSAC算法(openCV框架)实现物体的检测与定位,并求出变换矩阵(findFundamentalMat和findHomography的比较) 置顶

    原文链接:https://blog.csdn.net/qq_25352981/article/details/46914837#commentsedit 本文目标是通过使用SIFT和RANSAC算法, ...

  7. Unity5.6之前版本VRTK插件基础交互

    一.VR运行环境配置: 安装steam,在steam上安装SteamVR驱动. 在Unity项目中需要导入VRTool插件包(已上传服务器),里面包含两个插件一个是SteamVR插件,一个是VRTK插 ...

  8. net面试宝典

    ASP.NET常见面试题及答案 1. 简述 private. protected. public. internal 修饰符的访问权限. 答 . private : 私有成员, 在类的内部才可以访问. ...

  9. Redis学习笔记之入门基础知识——五种数据类型

    1) 字符串 SET设置值,GET获取值,DEL删除值 INCR key-name将键存储的值加上1       DECR key-name将键存储的值减去1 INCRBY key-name amou ...

  10. Linux内核分析——第三周学习笔记

    20135313吴子怡.北京电子科技学院 chapter1 知识点梳理 一.Linux内核源代码简介 (视频中对目录下的文件进行了简介,记录如下) arch目录 占有相当庞大的空间 arch/x86目 ...