Python文件操作相关问题

1、修改文件内容并写回原文件

1
2
3
4
5
6
7
with open(filename) as f:
file_str = f.read()
# do stuff with file_str
with open(filename, 'w') as f:
f.write(file_str)

2、重命名(移动/剪切)文件或文件夹

1
2
os.rename(src, dst)
shutil.move(src, dst)

3、删除文件或文件夹

1
2
3
os.remove() # will remove a file
os.rmdir() # will remove an empty directory
shutil.rmtree() # will delete a directory and all its contents

4、检查文件或文件夹是否存在

1
2
3
os.path.isfile(path) # check file exists
os.path.isdir(path) # check directory exsits
os.path.exists(path) # check file or directory exists

5、如果文件夹不存在则创建

1
2
if not os.path.exists(directory):
os.makedirs(directory)

6、检测文件夹为空则删除

1
2
3
4
try:
os.rmdir(directory)
except OSError:
pass

7、从路径中提取文件名和目录名

os.path.dirname(path)从path中提取目录,os.path.basename(path)从path中提取文件名。

1
2
3
4
5
6
>>> import os
>>> path = '/usr/bin/python'
>>> os.path.dirname(path)
'/usr/bin'
>>> os.path.basename(path)
'python'

os.path.split(path)分割路径成目录(os.path.dirname(path))和文件(os.path.basename(path))。

1
2
3
4
5
6
7
8
>>> import os
>>> path = '/usr/bin/python'
>>> head, tail = os.path.split(path)
>>> head
'/usr/bin'
>>> tail
'python'
>>>

8、复制文件

shutil.copyfile(src, dst) : Copy the contents (no metadata) of the file named src to a file named dst and return dst.

shutil.copy(src, dst) : Copies the file src to the file or directory dst.

shutil.copy2(src, dst) : Identical to copy() except that copy2() also attempts to preserve all file metadata.

shutil.copyfileobj(fsrc, fdst) : Copy the contents of the file-like object fsrc to the file-like object fdst.

9、统计某一文件夹下文件数量

1
2
3
>>> import os
>>> DIR = '/tmp'
>>> print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])

如统计文件夹数量,用os.path.isdir(path)做判断语句。

10、递归查找文件

Python 3.5+
从Python 3.5版本起,glob模块支持”**”语法,此时必须设置recursive标志。如果匹配的路径是list,则用glob.glob代替glob.iglob

1
2
3
4
import glob
for filename in glob.iglob('src/**/*.html', recursive=True)
print(filename)

Python 2.2 to 3.4
对于老版本从Python 2.2以上的,用os.walk递归遍历目标文件夹,然后用fnmatch.filter匹配简单的通配符表达式。

1
2
3
4
5
6
import fnmatch
import os
for root, dirnames, filenames in os.walk('src'):
for filename in fnmatch.filter(filenames, '*.py'):
print(os.path.join(root, filename))

11、按行读取文件内容到list并去除换行

1
2
with open(path) as f:
lines = f.read().splitlines()

12、检查文件夹下是否有文件

1
2
3
4
5
for root, dirnames, filenames in os.walk('.'):
if filenames:
print(root,'has files')
if not filenames:
print(root,'is empty')
大师兄 wechat
欢迎关注我的微信公众号:Python大师兄