您的位置:首页 > 编程语言 > Python开发

python 目录 文件操作大全

2017-11-10 10:15 579 查看
目录操作

1、得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()
>>> import os
>>> os.getcwd()
'/home/jack'
2、返回指定目录下的所有文件和目录名:os.listdir()

>>> os.listdir('/home/jack')
['.profile', '.bashrc', 'test', '.bash_logout']
3、函数用来删除一个文件:os.remove()

#创建文件 >>> os.mknod("t1.txt")

#显示当前目录下的所有文件

>>> os.listdir('/home/jack')

['.profile', '.bashrc', 't1.txt', 'test', '.bash_logout']

#删除文件
>>> os.remove("t1.txt")
>>> os.listdir('/home/jack')
['.profile', '.bashrc', 'test', '.bash_logout']

4、删除多个目录:os.removedirs(r“c:\python”)

#创建多个目录

>>> os.makedirs("t1/t2")
>>> os.listdir('/home/jack')
['.profile', '.bashrc', 't1', 'test', '.bash_logout']
>>> os.listdir('/home/jack/t1')
['t2']
#删除多个目录
>>> os.removedirs(r"/home/jack/t1/t2")

os.listdir('/home/jack')
['.profile', '.bashrc', 'test', '.bash_logout']
5、检验给出的路径是否是一个文件:os.path.isfile()
>>> os.path.isfile('.bashrc')
True
>>> os.path.isfile('.bashrc1')
False
6、检验给出的路径是否是一个目录:os.path.isdir()
>>> os.path.isdir('/home/jack/test')
True
>>> os.path.isdir('/home/jack/test1')
False
7、判断是否是绝对路径:os.path.isabs()
>>> os.path.isabs('/home/jack/test')
True
>>> os.path.isabs('test')
False
8、检验给出的路径是否真地存:os.path.exists()
>>> os.path.exists('test')
True
>>> os.path.exists('test1')
False
9、返回一个路径的目录名和文件名:os.path.split()
>>> os.path.split('/home/jack/test')
('/home/jack', 'test')

10、分离扩展名:os.path.splitext()
>>> os.path.splitext('/home/jack/test')
('/home/jack/test', '')

11、获取路径名:os.path.dirname()
>>> os.path.dirname('/home/jack/')
'/home/jack'

12、获取文件名:os.path.basename()
>>> os.mknod('a.txt')
>>> os.path.basename('/home/jack/a.txt')
'a.txt'
13、运行shell命令: os.system()
>>> os.system('ls -a')
. .. a.txt .bash_logout .bashrc .profile test

14、读取和设置环境变量:os.getenv() 与os.putenv()

getenv(key, default=None)
Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
15、重命名:os.rename(old, new)
>>> import os
>>> os.listdir("/home/jack")
['.profile', 'a.txt', '.bashrc', '.bash_history', '.ipython', 'test', '.bash_logout']
>>> os.rename('a.txt','b.txt')
>>> os.listdir('/home/jack')
['.profile', '.bashrc', '.bash_history', '.ipython', 'b.txt', 'test', '.bash_logout']

16、创建多级目录:os.makedirs()
>>> os.makedirs('t1/t2')
>>> os.listdir('/home/jack')
['.profile', '.bashrc', '.bash_history', '.ipython', 't1', 'b.txt', 'test', '.bash_logout']
>>> os.listdir('/home/jack/t1')
['t2']
17、创建单个目录:os.mkdir()
>>> os.mkdir('abc')
>>> os.listdir('/home/jack')
['.profile', 'abc', '.bashrc', '.bash_history', '.ipython', 't1', 'b.txt', 'test', '.bash_logout']

18、获取文件属性:os.stat(file)
>>> os.stat('b.txt')
posix.stat_result(st_mode=33152, st_ino=927137, st_dev=64769, st_nlink=1, st_uid=1001, st_gid=1001, st_size=0, st_atime=1510235921, st_mtime=1510235921, st_ctime=1510277660)

19、修改文件权限与时间戳:os.chmod(file)

参考博客:http://blog.csdn.net/wirelessqa/article/details/7974477

20、终止当前进程:os.exit()

21、获取文件大小:os.path.getsize(filename)

>>> os.path.getsize('b.txt')
0

文件操作
os.mknod("test.txt") #创建空文件
fp = open("test.txt",w) #直接打开一个文件,如果文件不存在则创建文件
r:以读方式打开文件,可读取文件信息。
w:以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容;如果文件不存在则创建
a:以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建
r+:以读写方式打开文件,可对文件进行读和写操作。
w+:消除文件内容,然后以读写方式打开文件。
a+:以读写方式打开文件,并把文件指针移到文件尾。
b:以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。

文件操作方法

常见文件操作方法:
方法
f.close() 关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。
f.name() 获取文件名称

f.next() 返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。

f.flush() 刷新输出缓存,把缓冲区的内容写入硬盘

f.isatty() 如果文件是一个终端设备文件(Linux系统中),则返回True,否则返回False。

f.read([size]) 读出文件,size为读取的长度,以byte为单位

f.readline([size]) 读出一行信息,若定义了size,则读出一行的一部分

f.readlines([size]) 读出所有行,也就是读出整个文件的信息。(把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分)

f.seek(offset[,where])

把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值;1表示当前位置;2表示文件结尾。(注意:如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾)

f.tell() 获得文件指针位置,标记当前位置,以文件开头为原点

f.truncate([size]) 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

f.write(string) 把string字符串写入文件,write()不会在str后加上一个换行符。

f.writelines(list) 把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

文件操作模式举例

w 模式,如果没有文件,会自动创建
>>> os.listdir('/home/jack')
['.profile', 'abc', '.bashrc', '.bash_history', '.ipython', 't1', 'b.txt', 'test', '.bash_logout']
>>> f1 = open('hello.txt','w')
>>> f1.write('hello world\n')
>>> f1.flush() #刷新输出缓存,把缓冲区的内容写入硬盘
>>> f1.close()
r 模式 只读模式
>>> f1 = open('hello.txt','r')
>>> print(f1.read())
hello world


r+ 模式 以读写方式打开文件,可对文件进行读和写操作。会清空原文件
>>> f1 = open('hello.txt','r+')
>>> f1.write('hello2 world\n')
>>> f1.close()
>>> f1 = open('hello.txt','r')
>>> print(f1.read())
hello2 world


w+ 模式 消除文件内容,然后以读写方式打开文件。
>>> f1 = open('hello.txt','w+')
>>> f1.write('hello world ,hello world\n')
>>> f1.close()

>>> f1 = open('hello.txt','r') >>> print(f1.read()) hello world ,hello world


a 模式 以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾)
如果文件不存在则创建,原有的文件内容保留
>>> f1 = open('hello.txt','a')
>>> f1.write('h2 h2\n')
>>> f1.close()
>>> f1 = open('hello.txt','r') >>> print(f1.read()) hello world ,hello world
h2 h2


a+ 模式 以读写方式打开文件,并把文件指针移到文件尾。
>>> f1 = open('hello.txt','a+')
>>> f1.write('h3 h3 h3\n')
>>> f1.close()
>>> f1 = open('hello.txt','r') >>> print(f1.read()) hello world ,hello world
h2 h2
h3 h3 h3
b :模式一般用于二进制文件的操作

文件读写方法

read # 读出所有文件,size为读取的长度,以byte为单位

readline #一行一行的读取

readlines #读出所有行,也就是读出整个文件的信息。(把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分)

f.write(string) 把string字符串写入文件,write()不会在str后加上一个换行符。 f.writelines(list) 把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息