介绍
open()函数用于打开文件并创建文件对象。
open()函数的语法格式:
file = open(filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
字符
解释
r
读取(默认)。文件必须存在
b
二进制模式。rb则表示以二进制模式读取。
w
写入。如果该文件已存在则会删除原有内容重新编辑。
x
写入。如果该文件已存在则报错。
a
追加写入。如果该文件已存在,在末尾追加写入;如果文件不存在,创建新文件写入。
b
二进制模式
t
文本模式(默认)
+
更新文件。可读可写。写入时,从文件开头覆盖原有内容
open()文件对象的方法
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!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章