python 目录文件操作

简介:

一、简介

   使用Python,经常会与文件和目录打交道,对于这些操作python提供了一个os模块,里面包含了很多操作文件和目录的函数。全部函数可以用help(os)或是dir(os)查看其用法.

二、代码示例 

     针对常用的函数操作进行了汇总。

#!/usr/bin/python
# encoding=utf-8
# Filename: dir_file.py
import os
import shutil


#操作目录
opDir=r'D:\test'

#创建目录
if not os.path.exists(opDir):
    os.mkdir(opDir)

#更改当前目录到opDir
os.chdir(opDir)

#显示当前目录
print '当前目录是:%s' % os.getcwd()

#创建多级目录
if not os.path.exists(opDir+os.sep+"aa"+os.sep+"bb"):
    os.makedirs(opDir+os.sep+"aa"+os.sep+"bb")
    
#在当前目录下创建文件
if not os.path.exists('test.txt'):
    f=open('test.txt',"w")
    f.write("write something to file")
    f.close()
    
#读取文件内容
print '文件内容如下:'
if os.path.exists('test.txt'):
    f=open('test.txt')
    while True:
        line = f.readline()
        if len(line) == 0: # Zero length indicates EOF
            break
        print line,
    f.close()

#打印一个空行
print '\n当前目录下的文件列表如下:'
#循环当前目录下的文件列表
lfile=os.listdir(os.getcwd())
for sfileName in lfile:
    if os.path.isdir(sfileName):
        print '目录%s' % sfileName
    elif os.path.isfile(sfileName):
        print '文件%s' % sfileName
        
#删除目录(只能删除空目录)
if os.path.exists("dd"):
    os.rmdir("dd")
    
#删除文件
if os.path.exists("aa"):
    shutil.rmtree("aa")
    
#修改目录或文件的名称
if os.path.exists("test"):
    os.rename("test", "test2")
    
#移动目录
if os.path.exists(r'D:\test'):
    shutil.move(r'D:\test',r'E:\test')

三、具体例子

http://my.oschina.net/max1984/blog/86132

Python删除指定目录下的过期文件(引用他人BLOG内容  )

服务器的文件每天不断增加,有很多文件碎片,需要定时清理,但还需要保留5天前的数据文件,用linux命令操作 


find /data/log -ctime +5 | xargs rm -f

会对系统造成很大压力,文件数会很多的说...

所以决定写个脚本,用crontab定时调用,来处理该需求

import os
import sys
import time
class DeleteLog:


    def __init__(self,fileName,days):
        self.fileName = fileName
        self.days = days
    def delete(self):
        if os.path.isfile(self.fileName):
            fd = open(self.fileName,'r')
            while 1:
                buffer = fd.readline()
                if not buffer : break
                if os.path.isfile(buffer):
                    os.remove(buffer)
            fd.close()
        elif os.path.isdir(self.fileName):
            for i in [os.sep.join([self.fileName,v]) for v in os.listdir(self.fileName)]:
                print i
                if os.path.isfile(i):
                    if self.compare_file_time(i):
                        os.remove(i)
                elif os.path.isdir(i):
                    self.fileName = i
                    self.delete()
    def compare_file_time(self,file):
        time_of_last_access = os.path.getatime(file)
        age_in_days = (time.time()-time_of_last_access)/(60*60*24)
        if age_in_days > self.days:
            return True
        return False
if __name__ == '__main__':
    if len(sys.argv) == 2:
        obj = DeleteLog(sys.argv[1],0)
        obj.delete()
    elif len(sys.argv) == 3:
        obj = DeleteLog(sys.argv[1],int(sys.argv[2]))
        obj.delete()
    else:
        print "usage: python %s listFileName|dirName [days]" % sys.argv[0]
        sys.exit(1)


目录
相关文章
|
12天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
17 1
|
17天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
25天前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
21 1
|
30天前
|
存储 并行计算 Java
Python读取.nc文件的方法与技术详解
本文介绍了Python中读取.nc(NetCDF)文件的两种方法:使用netCDF4和xarray库。netCDF4库通过`Dataset`函数打开文件,`variables`属性获取变量,再通过字典键读取数据。xarray库利用`open_dataset`打开文件,直接通过变量名访问数据。文中还涉及性能优化,如分块读取、使用Dask进行并行计算以及仅加载所需变量。注意文件路径、变量命名和数据类型,读取后记得关闭文件(netCDF4需显式关闭)。随着科学数据的增长,掌握高效处理.nc文件的技能至关重要。
109 0
|
1月前
|
Unix Linux 测试技术
Python超详细基础文件操作(详解版)(下)
Python超详细基础文件操作(详解版)
|
1月前
|
存储 JSON 数据库
Python超详细基础文件操作(详解版)(上)
Python超详细基础文件操作(详解版)
|
29天前
|
存储 安全 API
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
74 0
|
1天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
1天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
19 0
|
1天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
7 0