Python 工具箱系列(1):常用文件操作

1. 新建文件夹

1
2
if not os.path.isdir(path_out):
os.makedirs(path_out)

2. 遍历所有文件和子文件夹

1
2
for a, b, filenames in os.walk(path_data):
for filename in filenames:

3. 只遍历当前文件,不包含子文件夹

1
2
3
for a, b, filenames in os.walk(path_data):
for filename in filenames:
if a == path_data:

4. 读取文件的前几行或中间某些行

得到一个由迭代器生成的切片对象,标准切片不能做到。

1
2
3
4
5
import itertools

with open('/file/path') as f:
for line in itertools.islice(f, 2, None): # 遍历文件从第二行到最后一行
print line

5. 跳过拥有某些元素的行

在逐行读取文件时,我们可能要忽略掉拥有某些元素的行,通常一般的写法是:

1
2
3
4
with open('file/path') as f:
for line in f:
if line.startswith('#'):
print line

6. 判断是文件还是目录

判断路径是文件还是目录,不依赖于所处环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> os.path.exists("te")
True
>>> os.path.exists("nothing")
False
>>> os.path.isfile("nothing")
False
>>> os.path.isdir("nothing")
False
>>>
>>> os.path.isdir("te")
False
>>> os.path.isfile("te")
True
>>>

7. 遍历文件中的所有行

1
2
3
4
5
6
7
with open('foo.txt') as fp:
line = fp.readline()
n = 0
while line:
n += 1
print line
print n
------本文结束,欢迎收藏本站、分享、评论或联系作者!------
点击查看
赠人玫瑰 手有余香
0%