open()函数

介绍

open()函数用于打开文件并创建文件对象。

open()函数的语法格式:

file = open(filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
  • file: 创建的文件对象
  • filename: 要打开或创建的文件路径,需要加双引号或单引号。
  • mode: 可选项,指定文件打开模式。
字符 解释
r 读取(默认)。文件必须存在
b 二进制模式。rb则表示以二进制模式读取。
w 写入。如果该文件已存在则会删除原有内容重新编辑。
x 写入。如果该文件已存在则报错。
a 追加写入。如果该文件已存在,在末尾追加写入;如果文件不存在,创建新文件写入。
b 二进制模式
t 文本模式(默认)
+ 更新文件。可读可写。写入时,从文件开头覆盖原有内容
  • buffering: 可选整数,用于设置缓冲策略。0 关闭缓冲(只允许在二进制模式下), 1 表示表达式缓存(只在文本模式下可用),整数 > 1 表示固定大小的块缓冲区字节大小。负值为系统默认的寄存区缓冲大小。
  • encoding: 可选参数。文件编码方式,如"encoding="utf-8"。默认为GBK编码。

open()文件对象的方法

  • file.name: 返回文件名称
  • file.mode:返回文件打开模式
  • file.encoding: 返回文件打开的编码格式
  • file.close(): 关闭文件
  • file.closed: 判断文件是否关闭
  • file.read(size): 默认返回整个文件,size表示返回的字符个数。注:调用read()函数时,open()函数打开文件时的打开模式为"r"或"r+"。
  • file.readline():  返回一行。注:调用read()函数时,open()函数打开文件时的打开模式为"r"或"r+"。
  • file.readlines(size): 返回包含size大小的文本列表,默认返回整个文件列表,每个元素为文件的一行内容。注:调用read()函数时,open()函数打开文件时的打开模式为"r"或"r+"。
  • for line in file: print(line) #迭代访问
  • file.seek(offset, whence): 将文件指针移动到新的位置。offset指定移动的字符个数,whence指定从什么位置开始计算。0(默认值): 从文件开头计算;1:  从当前位置开始计算;2: 从文件尾开始计算。当open()函数打开文件时的打开模式没有用"b"时,则只能从文件头开始计算相对位置。
  • file.write(string): 向文件中写入string。注:调用write()函数时,open()函数打开文件时的打开模式为"w"或"a"。

python with语句与open()函数连用

使用open()函数打开文件后,要使用file.close()函数及时关闭,否则会出现意想不到的结果。另外,若打开的文件出现异常,会导致不能及时关闭文件。

with语句能够在处理文件时,无论是否出现异常,都能保证with语句执行完毕后关闭已打开的文件。

代码示例

编写含有以下内容名为learning_python.txt的文件

In Python you can construct function
In Python you can define class
In Python you can deal table

<一>

file_name = "learning_python.txt"
with open(file_name, mode="r") as file_object:
print(file_object.name)
print(file_object.mode)
print(file_object.encoding)
print(file_object.closed)

输出结果

learning_python.txt
r
cp936
False

<二>

file_name = "learning_python.txt"
with open(file_name, mode="r") as file_object:
"""读取文件的前9个字符"""
contents = file_object.read(9)
print(contents.rstrip())

输出结果

In Python

<三>

file_name = "learning_python.txt"
with open(file_name, mode="r") as file_object:
"""逐行读取"""
for line in file_object:
print(line.rstrip())

输出结果

In Python you can construct function
In Python you can define class
In Python you can deal table

<四>

file_name = "learning_python.txt"
with open(file_name, mode="r") as file_object:
"""逐行读取"""
num = 0
while True:
single_line = file_object.readline()
num += 1
if single_line == "":
break
print(single_line)

输出结果

In Python you can construct function

In Python you can define class

In Python you can deal table

<五>

file_name = "learning_python.txt"
with open(file_name, mode="r") as file_object:
"""创建一个包含文本的列表"""
lines = file_object.readlines()
print(lines)
pi_str = ""
for line in lines:
line = line.replace("Python", "Java")
pi_str += line
print(pi_str)
print(len(pi_str))

输出结果

['In Python you can construct function\n', 'In Python you can define class\n', 'In Python you can deal table']
In Java you can construct function
In Java you can define class
In Java you can deal table
90

<六>

file_name = "learning_python.txt"
with open(file_name, "r") as file_object:
file_object.seek(9)
print(file_object.read(12))

输出结果

 you can con

<七>

while True:
user_name = input("please input your name: ")
if user_name == "q":
break
else:
with open("users.txt","a") as file_object:
file_object.write("hello " + user_name + "!\n")

执行上述脚本后依次输入"lele","xiaohua"和"q",返回一个users.txt文件,内容包括:

hello lele!
hello xiaohua!

python内置函数open()的更多相关文章

  1. python内置函数

    python内置函数 官方文档:点击 在这里我只列举一些常见的内置函数用法 1.abs()[求数字的绝对值] >>> abs(-13) 13 2.all() 判断所有集合元素都为真的 ...

  2. python 内置函数和函数装饰器

    python内置函数 1.数学相关 abs(x) 取x绝对值 divmode(x,y) 取x除以y的商和余数,常用做分页,返回商和余数组成一个元组 pow(x,y[,z]) 取x的y次方 ,等同于x ...

  3. Python基础篇【第2篇】: Python内置函数(一)

    Python内置函数 lambda lambda表达式相当于函数体为单个return语句的普通函数的匿名函数.请注意,lambda语法并没有使用return关键字.开发者可以在任何可以使用函数引用的位 ...

  4. [python基础知识]python内置函数map/reduce/filter

    python内置函数map/reduce/filter 这三个函数用的顺手了,很cool. filter()函数:filter函数相当于过滤,调用一个bool_func(只返回bool类型数据的方法) ...

  5. Python内置函数进制转换的用法

    使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...

  6. Python内置函数(12)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string  ...

  7. Python内置函数(61)——str

    英文文档: class str(object='') class str(object=b'', encoding='utf-8', errors='strict') Return a string ...

  8. 那些年,很多人没看懂的Python内置函数

    Python之所以特别的简单就是因为有很多的内置函数是在你的程序"运行之前"就已经帮你运行好了,所以,可以用这个的特性简化很多的步骤.这也是让Python语言变得特别的简单的原因之 ...

  9. Python 内置函数笔记

    其中有几个方法没怎么用过, 所以没整理到 Python内置函数 abs(a) 返回a的绝对值.该参数可以是整数或浮点数.如果参数是一个复数,则返回其大小 all(a) 如果元组.列表里面的所有元素都非 ...

  10. 【转】实习小记-python 内置函数__eq__函数引发的探索

    [转]实习小记-python 内置函数__eq__函数引发的探索 乱写__eq__会发生啥?请看代码.. >>> class A: ... def __eq__(self, othe ...

随机推荐

  1. 为什么JAVA中(byte)128结果为-128;(byte)-129结果为127

    为什么JAVA中(byte)128结果为-128;(byte)-129结果为127 在JAVA中默认的整型为int型,int型占4个字节,为32位.byte占一个字节为8位. JAVA中的二进制都是采 ...

  2. java 泛型使用

    泛型类 // 简单泛型 class Point<T>{ // 此处可以随便写标识符号,T是type的简称 private T var ; public T getVar(){ return ...

  3. locust socektio协议压测

    # -*-coding:UTF-8 -*- from locust import HttpLocust, TaskSet, task, TaskSequence, Locust, events imp ...

  4. Python学习笔记之7.5 - 定义有默认参数的函数》》》直接在函数定义中给参数指定一个默认值,默认参数的值应该是不可变的对象

    问题: 你想定义一个函数或者方法,它的一个或多个参数是可选的并且有一个默认值. 解决方案: 定义一个有可选参数的函数是非常简单的,直接在函数定义中给参数指定一个默认值,并放到参数列表最后就行了.例如: ...

  5. Http 包头里面有个content-length,可以获取下载的资源包大小

    NSDictionary *headerFieldsDic = request.responseHeaders; 包大小为:[headerFieldsDic[@"Content-Length ...

  6. vue后台管理系统

    1. 项目概述: 根据不同的应用场景,电商系统一般都提供了 PC 端.移动 APP.移动 Web.微信小程序等多种终端访问方式. 2. 电商后台管理系统的功能 电商后台管理系统用于管理用户账号.商品分 ...

  7. FastReport和RDLC报表

    最近在做报表的时候第一次接触到RDLC报表,对比于之前使用的FastReport报表来说,在使用体验上个人目前感觉RDLC灵活性相对较差,尤其是表格的格式多样的时候,不易修改.RDLC应用于格式简单的 ...

  8. linux Usb serial console

    ubuntu Usb serial console 能够把下电时打印输出到串口上,可以记录,而netconsole只能输出下电到disk 之前的打印 Usb串口线,ftdi或pl2303都可以 如果是 ...

  9. Maven将项目包deploy到nexus私服

    maven配置 打开maven安装目录下面的settings.xml,在servers中添加配置.如下: pom配置 在pom文件中加入distributionManagement配置,注意:这里的i ...

  10. 几行python代码完美操控手机

    最近一直成谜于python代码带来的便利,今天打算学习下用python代码来控制操作手机,首先需要利用adb,通过安卓调试桥来达到目的,其实也可以用appium来实现,不过appium多数用在自动化测 ...