python 文件与文件夹常见操作以及os.walk的用法

时间:2024-09-23 18:05:02

文件操作:

In [34]: import os

In [35]: os.rename("hello[复件].py","hello111.py")       ###重命名

In [36]: ls
copy_file.py hello111.py hello.py langwang.txt langwang[复件].txt

In [37]: os.remove("hello111.py")              ###删除文件

In [38]: ls
copy_file.py hello.py langwang.txt langwang[复件].txt

#########################################

文件夹操作:

In [39]: os.mkdir("tool")          ###创建文件夹

In [40]: ls
copy_file.py hello.py langwang.txt langwang[复件].txt tool/

In [42]: os.rmdir("tool")         ###删除文件夹

In [43]: ls
copy_file.py hello.py langwang.txt langwang[复件].txt

In [41]: os.getcwd()              ###获取当前路径
Out[41]: '/home/script'

In [44]: os.chdir("/root")     ###改变当前路径

In [45]: os.getcwd()     
Out[45]: '/root'

In [46]: os.listdir('/home/script/')    ###获取目录列表的内容
Out[46]:
['copy_file.py',
'hello.py',
'langwang.txt',
'langwang[\xe5\xa4\x8d\xe4\xbb\xb6].txt']

##############os.walk用法实例###############

#!/usr/bin/python
# -*- coding:utf-8 -*- import os
from os.path import join, getsize
for root, dirs, files in os.walk('/home/script'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories