f = open('test.txt') # 访问方式可以省略,默认以r(只读)的形式 f = open('test.txt', 'w') f = open('test.txt', 'w', encoding="utf-8")
encoding默认时使用与操作系统一样的编码方式,window为gbk,linux为utf-8。在window中有的ide编码为utf-8,则在操作文件时需要额外设置encoding="utf-8"
|访问方式| 说明 |
|--|--|
| r | 以只读方式打开文本文件。文件的指针将会放在文件的开头。这是默认模式。 |
| w| 打开一文本个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 |
| a| 打开一个文本文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。|
若要操作二进制文件(图片、视频等非文本文件),则在后面加b即可,例如rb,wb,ab。
若要想对文件又读又写,则在后面加+号,例如r+,w+,a+,rb+,wb+,ab+.
f.close()
关闭后的文件不能再进行读写操作, 否则会触发 valueerror 错误。
# 以文本文件打开 f = open('test.txt', 'w', encoding="utf-8") f.write('hello world, i am here!') f.close() # 以二进制文件打开 f = open('test.txt', 'wb') f.write('hello world, i am here!'.encode("utf-8")) f.close()
f = open('test.txt') content = f.read(5) print(content) print("-"*30) content = f.read() print(content) f.close() """ 输出结果: hello ------------------------------ world, i am here! """
注意:如果读取了多次数据,那么后面读取的数据是从上次读完后的位置开始的
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
示例如下:
f = open('test.txt', 'r') content = f.readline() print(content) print("-"*30) content = f.readline() print(content) f.close() """ 输出结果: 1:www.runoob.com ------------------------------ 2:www.runoob.com """
f = open('test.txt', 'r') content = f.readlines() print(content) f.close() """ 输出结果: ['1:www.runoob.com\n', '2:www.runoob.com\n', '3:www.runoob.com\n', '4:www.runoob.com\n', '5:www.runoob.com'] """
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
f = open("test.txt", "r") str = f.read(3) print("读取的数据是 : ", str) # 查找当前位置 position = f.tell() print("当前文件位置 : ", position) str = f.read(3) print("读取的数据是 : ", str) # 查找当前位置 position = f.tell() print("当前文件位置 : ", position) f.close() """ 读取的数据是 : 1:w 当前文件位置 : 3 读取的数据是 : ww. 当前文件位置 : 6 """
注意:文件位置从0开始记
f = open("test.txt", "r") str = f.readline() print("读取的数据是 : ", str) # 查找当前位置 position = f.tell() print("当前文件位置 : ", position) # 重新设置位置 f.seek(0, 0) # 查找当前位置 position = f.tell() print("当前文件位置 : ", position) str = f.readline() print("读取的数据是 : ", str) f.close() """ 输出结果: 读取的数据是 : 1:www.runoob.com 当前文件位置 : 18 当前文件位置 : 0 读取的数据是 : 1:www.runoob.com """
有时候需要对文件进行重命名、删除等操作时,要用到我们python中的os模块,os 模块提供了非常丰富的方法用来处理文件和目录。
import os # 将文件a重命名为文件b os.rename("a.txt","b.txt")
import os os.remove("a.txt")
实际开发中,有时需要用程序的方式对文件夹进行一定的操作,比如创建、删除等就像对文件操作需要os模块一样,如果要操作文件夹,同样需要os模块。
import os os.mkdir("文件夹")
import os os.getcwd()
# 表示跳到上一级目录 os.chdir("../")
import os # 不传入参数时,返回当前的路径的列表 os.listdir(path)
import os os.rmdir("文件夹")
如对本文有疑问, 点击进行留言回复!!
Python sqlalchemy时间戳及密码管理实现代码详解
网友评论