day3-python-文件操作(2)
本文内容涉及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: ./test1dirs: ['test11']files: []top: ./test1/test11dirs: ['test111']files: []top: ./test1/test11/test111dirs: []files: []top: ./test3dirs: []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)的更多相关文章
- Python基础篇【第2篇】: Python文件操作
Python文件操作 在Python中一个文件,就是一个操作对象,通过不同属性即可对文件进行各种操作.Python中提供了许多的内置函数和方法能够对文件进行基本操作. Python对文件的操作概括来说 ...
- [Python学习笔记][第七章Python文件操作]
2016/1/30学习内容 第七章 Python文件操作 文本文件 文本文件存储的是常规字符串,通常每行以换行符'\n'结尾. 二进制文件 二进制文件把对象内容以字节串(bytes)进行存储,无法用笔 ...
- Python文件操作与函数目录
文件操作 python文件操作 函数 Python函数学习——初步认识 Python函数学习——作用域与嵌套函数 Python函数学习——匿名函数 python内置函数 Python函数学习——递归 ...
- 初学Python——文件操作第二篇
前言:为什么需要第二篇文件操作?因为第一篇的知识根本不足以支撑基本的需求.下面来一一分析. 一.Python文件操作的特点 首先来类比一下,作为高级编程语言的始祖,C语言如何对文件进行操作? 字符(串 ...
- day8.python文件操作
打开和关闭文件 open函数 用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写. file = open(file_name [, access_ ...
- 关于python 文件操作os.fdopen(), os.close(), tempfile.mkstemp()
嗯.最近在弄的东西也跟这个有关系,由于c基础渣渣.现在基本上都忘记得差不多的情况下,是需要花点功夫才能弄明白. 每个语言都有相关的文件操作. 今天在flask 的例子里看到这样一句话.拉开了文件操作折 ...
- Python之路Python文件操作
Python之路Python文件操作 一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r&qu ...
- python 文件操作 r w a
python基础-文件操作 一.文件操作 对文件操作的流程 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 打开文件时,需要指定文件路径和以何等方式打开文件, ...
- Python:文件操作技巧(File operation)(转)
Python:文件操作技巧(File operation) 读写文件 # ! /usr/bin/python # -*- coding: utf8 -*- spath = " D:/dow ...
- 小学生都能学会的python(文件操作)
小学生都能学会的python(文件操作) 1. open("文件路径", mode="模式", encoding="编码") 文件的路径: ...
随机推荐
- spring 的redis操作类RedisTemplate
spring 集成的redis操作几乎都在RedisTemplate内了. 已spring boot为例, 再properties属性文件内配置好 redis的参数 spring.redis.host ...
- 【转】不用程序mysql也可以查询今天、昨天、7天、近30天、本月、上一月的数据
今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NO ...
- Kmeans原理与实现
原理 http://www.cnblogs.com/jerrylead/archive/2011/04/06/2006910.html 实现 http://www.cnblogs.com/zjutzz ...
- jQuery多项选项卡的实现
请勿盗版.转载请加上出处http://blog.csdn.net/yanlintao1 请勿盗版,转载请加上出处http://blog.csdn.net/yanlintao1 css样式: @CHAR ...
- poj 2503 Babelfish(字典树或着STL)
Babelfish Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 35828 Accepted: 15320 Descr ...
- 使用c++为node.js扩展模块
官方文档 编写c++代码 // demo.cc #include <node.h> using v8::FunctionCallbackInfo; using v8::Isolate; u ...
- python bottle学习(三)动态路由配置(通配符)
from bottle import (run, route, get, post, default_app, Bottle) @route('/', method='GET') @route('/i ...
- 认识tornado(一)
tornado 源码包中 demos 目录下包含一些示例程序,就从最简单的 helloworld.py 来看一个 tornado 应用程序的代码结构. 完整的实例程序如下: 01 #!/usr/bin ...
- jquery 轮播图实例
实现效果:1.图片每2秒钟切换1次. 2.当鼠标停留在整个页面上时,图片不进行轮播. 3.当点击右下角的小球时,出现该选项的对应图片,而且切换页选项的背景颜色发生相应的变化. 4.当图片发生轮播切换时 ...
- Dart基础学习01--走近Dart
什么是Dart 在Dart的官网上是这样介绍Dart的: Dart is an open-source, scalable programming language, with robust libr ...