本文内容涉及python中的os模块和os.path模块的常用操作,这两个模块提供了与平台和操作系统无关的文件系统访问方法。os模块负责大部分的文件系统操作,包括:删除文件、重命名文件、遍历目录树等;os.path模块提供了一些针对路径名的操作,包括:获取文件和子目录信息,文件路径查询等。
1. os模块

remove(path) 删除文件
rename(src,dst) 重命名文件
renames(old,new) 递归重命名目录或文件
walk(top,topdown=True,onerror=None,followlinks=False) 返回指定目录下每次遍历的路径名、目录列表、文件列表,top为指定的顶层目录,topdown表示自顶向下遍历,onerror指定异常函数,followlinks是否递归遍历链接文件。
chdir(path) 改变当前工作目录
listdir(path) 列出指定目录的文件和目录
getcwd() 返回当前工作目录
mkdir(path,mode=0o777) 创建目录
makedirs(path,mode=0o777) 递归创建目录
rmdir(path) 删除目录
removedirs(path) 递归删除目录

实例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
>>> import os
>>> os.listdir('.')
[]
>>> os.mkdir('test1')
>>> os.makedirs('test2/test21/test211')
>>> os.listdir('.')
['test2', 'test1']
>>> os.listdir('./test2')
['test21']
  
>>> open('test.txt','w')
<open file 'test.txt', mode 'w' at 0x7faa26f69930>
>>> os.listdir('.')
['test2', 'test1', 'test.txt']
>>> os.remove('test.txt')
>>> os.listdir('.')
['test2', 'test1']
>>> os.getcwd()
'/home/alexzhou/study_workspace/python/test'
>>> os.chdir('./test1')
  
>>> os.getcwd()
'/home/alexzhou/study_workspace/python/test'
>>> os.rename('test1','test3')
>>> os.listdir('.')
['test2', 'test3']
  
>>> os.renames('test2/test21/test211','test1/test11/test111')
>>> os.listdir('.')
['test1', 'test3']
>>> os.listdir('test1')
['test11']
>>> os.listdir('test1/test11')
['test111']
  
>>> open('test3/test.txt','w')
<open file 'test3/test.txt', mode 'w' at 0x7faa26f69930>
>>> for top,dirs,files in os.walk('.'):
...     print 'top:',top
...     print 'dirs:',dirs
...     print 'files:',files
...
top: .
dirs: ['test1', 'test3']
files: []
top: ./test1
dirs: ['test11']
files: []
top: ./test1/test11
dirs: ['test111']
files: []
top: ./test1/test11/test111
dirs: []
files: []
top: ./test3
dirs: []
files: ['test.txt']
  
>>> os.remove('test3/test.txt')
>>> os.rmdir('test3')
>>> os.listdir('.')
['test1']
>>> os.removedirs('test1/test11/test111')
>>> os.listdir('.')
[]

2. os.path模块

basename(path) 去掉目录路径,返回文件名
dirname(path) 去掉文件名,返回目录路径
join(*path) 将分离的各部分组合成一个路径名
split(path) 返回(dirname(),basename())元组
splitdrive(path) 返回(drivename,pathname)元组
splitext(path) 返回(filename,extension)元组
exists(path) 指定文件或目录是否存在
isabs(path) 指定路径是否是绝对路径
isdir(path) 指定路径是否存在且是一个目录
isfile(path) 指定路径是否存在且是一个文件
islink(path) 指定路径是否存在且是一个符号链接
samefile(path1,path2) 两个路径名是否指向同一个文件

实例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> os.path.basename('/home/zhoujianghai/study_workspace/python/test_file.py')
'test_file.py'
>>> os.path.dirname('/home/zhoujianghai/study_workspace/python/test_file.py')
'/home/zhoujianghai/study_workspace/python'
  
>>> os.path.join('home','zhoujianghai','study_workspace')
'home/zhoujianghai/study_workspace'
  
>>> os.path.split('/home/zhoujianghai/study_workspace/python/test_file.py')
('/home/zhoujianghai/study_workspace/python', 'test_file.py')
>>> os.path.splitdrive('/home/zhoujianghai/study_workspace/python/test_file.py')
('', '/home/zhoujianghai/study_workspace/python/test_file.py')
  
>>> os.path.splitext('/home/zhoujianghai/study_workspace/python/test_file.py')
('/home/zhoujianghai/study_workspace/python/test_file', '.py')
  
>>> os.path.samefile('../test_file.py','../test_file.py')
True
>>> os.path.exists('../test_file.py')
True

下面是统计指定目录下文件数和代码行数的小例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import sys,os
  
def count_file_lines(filepath):
    ret = 0
    f = open(filepath,"r")
    for lines in f:
        if lines.split():
            ret += 1
    return ret
  
if __name__ == '__main__':
    top = './'
    total_lines = 0
    total_files = 0
    for root,dirs,files in os.walk(top):
        for filename in files:
            ext = os.path.splitext(filename)[-1]
            if ext in ['.py']:
                filepath = root + os.sep + filename
                total_files += 1
                total_lines += count_file_lines(filepath)
  
    print 'Total lines:',total_lines
    print 'Total files: ',total_files

day3-python-文件操作(2)的更多相关文章

  1. Python基础篇【第2篇】: Python文件操作

    Python文件操作 在Python中一个文件,就是一个操作对象,通过不同属性即可对文件进行各种操作.Python中提供了许多的内置函数和方法能够对文件进行基本操作. Python对文件的操作概括来说 ...

  2. [Python学习笔记][第七章Python文件操作]

    2016/1/30学习内容 第七章 Python文件操作 文本文件 文本文件存储的是常规字符串,通常每行以换行符'\n'结尾. 二进制文件 二进制文件把对象内容以字节串(bytes)进行存储,无法用笔 ...

  3. Python文件操作与函数目录

    文件操作 python文件操作 函数 Python函数学习——初步认识 Python函数学习——作用域与嵌套函数 Python函数学习——匿名函数 python内置函数 Python函数学习——递归 ...

  4. 初学Python——文件操作第二篇

    前言:为什么需要第二篇文件操作?因为第一篇的知识根本不足以支撑基本的需求.下面来一一分析. 一.Python文件操作的特点 首先来类比一下,作为高级编程语言的始祖,C语言如何对文件进行操作? 字符(串 ...

  5. day8.python文件操作

    打开和关闭文件 open函数 用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写. file = open(file_name [, access_ ...

  6. 关于python 文件操作os.fdopen(), os.close(), tempfile.mkstemp()

    嗯.最近在弄的东西也跟这个有关系,由于c基础渣渣.现在基本上都忘记得差不多的情况下,是需要花点功夫才能弄明白. 每个语言都有相关的文件操作. 今天在flask 的例子里看到这样一句话.拉开了文件操作折 ...

  7. Python之路Python文件操作

    Python之路Python文件操作 一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r&qu ...

  8. python 文件操作 r w a

    python基础-文件操作   一.文件操作 对文件操作的流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件       打开文件时,需要指定文件路径和以何等方式打开文件, ...

  9. Python:文件操作技巧(File operation)(转)

    Python:文件操作技巧(File operation) 读写文件 # ! /usr/bin/python #  -*- coding: utf8 -*- spath = " D:/dow ...

  10. 小学生都能学会的python(文件操作)

    小学生都能学会的python(文件操作) 1. open("文件路径", mode="模式", encoding="编码") 文件的路径: ...

随机推荐

  1. C# 个人疏漏整理

    1.dynamic和var不能混为一谈. var声明局部变量只是一种简化语法,var要求编译器根据之后的表达式推断具体的数据类型. var只能用于声明方法内部的局部变量,dynamic则可用于局部变量 ...

  2. linux引导模式两种

    https://www.ibm.com/developerworks/cn/linux/l-bootload.html

  3. Docker是用来干什么的?【快速入门】

    Docker从去年开始不仅能在Linux下运行 ,还支持windows.osX等主流系统. 下面的例子我自己经常使用,当然你有更好的案例也可以分享给我. 尝试新软件 对开发者而言,每天会催生出的各式各 ...

  4. SyncML 同步协议 感谢 周鹏(我只是做一个备份)

    SyncML 同步协议(SyncML Sync Protocol) 翻译周鹏 2006-1-24 摘要 本规范定义了SyncML客户和服务的同步协议. 它规范了怎样使用SynML表示层协议去完成Syn ...

  5. Tuning 05 Sizing other SGA Structure

    Redo Log Buffer Content The Oracle server processes copy redo entries from the user’s memory space t ...

  6. JQ 报表插件 jquery.jqplot 使用

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...

  7. html 简单的预缓存

    切图生成html,加鼠标响应,预缓存 <style> .d4{ width:190; height:170; background-image: url(images/未标题-1_09-1 ...

  8. linux运维/自动化开发__目录

    服务器软件安装 nginx apache php mysql oracle tomcat memcached mongodb sqlserver 常用pc端工具安装使用 Xshell         ...

  9. 解决百度地图Fragment切换黑屏问题

    https://blog.csdn.net/rentalphang/article/details/52076330 轻松解决啦!

  10. python的猴子补丁monkey patch

    monkey patch指的是在运行时动态替换,一般是在startup的时候. 用过gevent就会知道,会在最开头的地方gevent.monkey.patch_all();把标准库中的thread/ ...