python os模块打开文件_Python 文件操作之OS模块

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模块打开文件)