with open('filepath') as rename:

for line in rename:

...

with 命令下 不用使用close()函数关闭文件,打开的文件在with 代码块下有效。

python OS 模块:(import os)

os.getcwd() # return the current working dictionary

os.chdir(path) # change the current working dictionary to the specified path

os.listdir(path='...') # Return alist containing the names of the files in the directory

os.mkdir(pah,[mode]) # 创建单层目录

os.makedirs(path,[mode]) # super mkdr() 递归创建多层目录

remove(path) # 删除文件

rmdir(path) # 删除单层 空 目录,非空目录抛出异常

removedirs(path) # 递归删除多层 空 目录

rename(old, new) # 重命名, 可通过该命令进行文件赋值

system(command) # 运行系统命令

--------------------------------------------------------------------------------------------------------------------------

os.curdir #常量 ‘.’ 指代当前目录

os.aprdir # 常量 ‘..’ 指代上级目录

os.name #指代当前 操作系统

os.linesep #系统换行符

os.sep #系统 路径分隔符

===============================================================================

os.path 模块

basename(path) #去掉目录路径, 单独返回文件名

dirname(path) #去掉文件名 返回路径

join('path1', 'path2',...) #将输入的字符床 path1、path2 组成路径返回

split(path) # 分割文件路径 返回元组 不会判断路径是否存在

splittext(path) #分离文件名与扩展名 返回元组、

getsize(file) # 返回文件大小

getatime(file) # 返回最近访问时间(time.localtime(float)得到时间)

getctime(file) #返回文件创建时间

getmtime(file) # 返回文件修改时间

-----------------------------------------------------------------------------------------------------------------------------

exists(path) #判断指定路径是否存在

isabs(path) #判断是否为绝对路径

isdir(path)

isfile(path)

islink(path)

ismount(path)

samefile(path1, path2) # 两个路径是否指向同一个文件

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

pickle: 存取二进制文件

pickle.dump(data, file_object)

pickle.load()

通过OS 模块及 os.path模块下的方法 查看当前目录的文件,并按照文件修改时间排序:代码如下。

importosimporttimeprint(os.getcwd())

dirs_list=os.listdir()

file_modify_time=[]for dir indirs_list:#print(dir + ': '+ str(os.path.getsize(dir)))

dict_time = {'name': dir, 'mtime': os.path.getmtime(dir)} #将文件信息组成字典

file_modify_time.append(dict_time) #append 进入事先定义的列表中#print(file_modify_time)

def sorted_seed(file_modify_time): #为排序函数 sorted() 中的 key 参数定义 种子函数

return file_modify_time['mtime']defsorted_file_with_mtime(file_modify_time):

results= sorted(file_modify_time, key = sorted_seed) #通过sorted() 函数 及其种子函数按 列表中字典的时间值 排序

returnresults

results=sorted_file_with_mtime(file_modify_time)for result inresults:

year, mon, day, hour, mint, sec, wday, yday, isdst= time.localtime(result['mtime']) #time.localtimae()得到的时间参数 解构

print('{0}\n{1:>}'.format(result['name'],str(year) + '.' + str(mon) + '.' + str(day) + '——' + str(hour) + ':' + str(mint) + ':' + str(sec))) #format函数打印结果

通过定义类的方式 实现。

#代码优化

importosimportpickle#定义一个文件信息查看 类

classFile_check():

num=0#记录对象 个数

def __init__(self):

self.__class__.num += 1

#通过 os 的 内置函数 获取路径内文件信息

def __get_file_list(self, path):ifos.path.exists(path):

file_message_list=[]

file_name_list=os.listdir(path)for name infile_name_list:

dict_time= {'name': name, 'mtime': os.path.getmtime(name)}

file_message_list.append(dict_time)else:print("Wrong path, dosn't exist")

file_message_list=Nonereturnfile_message_list#对文件进行排序 按照文件的修改时间

def __sorted_file(self, file_message_list):if file_message_list ==None:

sorted_file_list=Noneelif notfile_message_list:print('Empty dir')

sorted_file_list=[]else:#通过 sorted 函数进行排序 , 为 key 参数构建一个种子函数

sorted_file_message_list = sorted(file_message_list, key = self.__sorted_seed)returnsorted_file_message_list#种子函数

def __sorted_seed(self, file):return file['mtime']#结果显示

def __show_results(self, sorted_file_message_list):for result insorted_file_message_list:print(result)#结果存入文件

def __results_write2_file(self, sorted_file_message_list):

with open('test.log', mode='wb') as f:

pickle.dump(sorted_file_message_list,f)#入口程序

defrun(self, path):

file_list= self.__get_file_list(path)

sorted_file_message_list= self.__sorted_file(file_list)

self.__results_write2_file(sorted_file_message_list)

self.__show_results(sorted_file_message_list)

file=File_check()

os.chdir('D:')

file.run(os.getcwd())

python os模块打开文件_Python 文件操作之OS模块相关推荐

  1. python创建文件os_Python之文件与目录操作(os、zipfile、tarfile、shutil)

    Python中可以用于对文件和目录进行操作的内置模块包括: 模块/函数名称功能描述 open()函数 文件读取或写入 os.path模块 文件路径操作 os模块 文件和目录简单操作 zipfile模块 ...

  2. python可以处理哪些文件_python文件处理

    1.python文件概念 python中文件就是一个对象,而linux中一切设备都可以看成文件,例如:磁盘文件,管道,网络Socket,外设等,都可以使用文件的方式对其进行操作.linux中文件的属性 ...

  3. python在windows 输入和输出文件_Python文件、目录和输入输出操作

    读取键盘的输入 Python提供了input()内置函数从标准输入读入一行文本,默认的标准输入是键盘.input可以接收一个Python表达式作为输入,并将运算结果返回,如下所示: biotest@b ...

  4. python以读写方式打开文件_python 文件读写with open模式r,r+,w,w+,a,a+的区别

    原博文 2020-07-31 17:49 − 模式可做操作若文件不存在是否覆盖 r 只能读 报错 - r+ 可读可写 报错 是 w 只能写 创建 是 w+ 可读可写 创建 是 a 只能写 创建 否,追 ...

  5. python读取写入文件_Python文件读写保存操作

    记录下第一次使用Python读写文件的过程,虽然很简单,第一次实现其实也有些注意的事项. 单个文件的读操作: 我们先假设一个需求如下: 读取一个test.txt文件 删除指定字符之前的文本 需求明白之 ...

  6. python open可以打开什么类型文件_Python打开文件open()的注意事项

    原博文 2018-02-28 10:51 − 刚刚用open(fileName)来打开txt格式的文件,总是出现错误,总是找不到文件读取的内容,后来才发现是open()在使用过程中自动关闭了.这里介绍 ...

  7. python展示文件_python 文件操作实力显示

    文件的操作 关键字:open("文件名称",mode="操作",encoding= "编码方式" 操作1: mode= w :(写) w+: ...

  8. python以读写方式打开文件_python文件读写

    打开文件 file_object = open(file_name, access_mode='r', buffering=-1) 功能:打开一个文件,返回一个文件对象. 参数:file_name 文 ...

  9. python 读取文件名 指定编码_Python 文件读写与编码解读

    一.Python 读取文件使用open函数 python open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写. open(name[,mode[,buffer ...

最新文章

  1. Redis 安装详细过程(redis基本使用(服务端和客户端)、修改密码)
  2. Java中对象的销毁
  3. 应用DIV+CSS编码时容易犯的一些错误
  4. 笔试训练1 知识点整理
  5. hadoop yarn 获取日志_赵丽颖固然漂亮,可这份Hadoop核心教程也不差啊!
  6. 【CodeForces - 305C】Ivan and Powers of Two(思维,STL,set,优先队列)
  7. 安卓倒计时 listview默认选中一项
  8. Java WebSocket生命周期
  9. ADB常用命令及其用法大全
  10. 布局之StackPanel面板
  11. 说好的弯曲损耗不敏感呢!入户皮线光缆的衰耗从何而来?
  12. java 调用宏_通过java代码实现调用excel当中的宏的操作。
  13. 计算机电源 通电,笔记本电脑开不了机,通电后电源指示灯不亮
  14. 区块链平台架构设计的知识图谱
  15. 解析为何支付宝微信二维码合一
  16. faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException问题解决
  17. 如何在百度地图、腾讯地图标注公司地址信息?
  18. Servlet+JSP项目
  19. LINUX下设置postgresql的登录密码
  20. 分享个梦塔防挂机辅助,快速升级升段刷资源的脚本

热门文章

  1. 栈和堆(Stack Heap)
  2. CactiEZ中文版10.1与CAS单点登录
  3. u3d一个GameObject绑定两个AudioSource
  4. 【毕业答辩】毕业设计答辩前期准备
  5. 我用Python写了一个邮箱脚本发给班花,没想到事情闹大了...
  6. java正则和python正则差距,在C/Java中处理正则表达式比在Python中快多少?
  7. 制备石墨烯流程图_科研人员制备出小扭转角度双层石墨烯
  8. Python: PIL基本代码
  9. Python+OpenCV:理解支持向量机(SVM)
  10. php socket keepalive,使用keepalive和fastcgi_keep_conn打开Nginx php-fpm时出错