浅谈python中文件和文件夹的相关操作
文件操作文件的打开与关闭
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"
f.close() 关闭后的文件不能再进行读写操作, 否则会触发 ValueError 错误。 文件的读写
# 以文本文件打开 f = open('test.txt',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! """ 注意:如果读取了多次数据,那么后面读取的数据是从上次读完后的位置开始的
示例如下: 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.comn','2:www.runoob.comn','3:www.runoob.comn','4:www.runoob.comn','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("读取的数据是 : ",position) f.close() """ 读取的数据是 : 1:w 当前文件位置 : 3 读取的数据是 : ww. 当前文件位置 : 6 """ 注意:文件位置从0开始记
f = open("test.txt","r") str = f.readline() 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("文件夹") (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |