从目录中读取所有文件(使用不同的cwd)

时间:2013-09-28 08:23:56

标签: python

以下代码是读取目录中的所有文件,但问题是我的cwd是/home/kumarswamys/Adobe(我存储的是readdir.py)但是我想读取/home/kumarswamys/Adobe/download中的文件,但是我无法读取这些文件,因为cwd是/home/kumarswamys/Adobe,它没有说明这样的文件或目录

我尝试加入这条路但不行,请任何人帮助我....?      readdir.py

 #!/usr/bin/env python
 import os

 path = '/home/kumarswamys/Adobe/download'  
 for subdir, dirs, files in os.walk(path):
 for file in files:
    print file
    f=open(file, 'r')
    f.readlines()
    f.close()

2 个答案:

答案 0 :(得分:0)

使用os.path.join(subdir, filename)获取路径:

>>> os.path.join('/home/kumarswamys/Adobe/download', 'filename.txt')
'/home/kumarswamys/Adobe/download/filename.txt'

import os

path = '/home/kumarswamys/Adobe/download'  
for subdir, dirs, files in os.walk(path):
    for filename in files:
        filepath = os.path.join(subdir, filename) # <-----
        with open(filepath, 'r') as f:
            lines = f.readlines()

答案 1 :(得分:0)

import glob
path = '/home/kumarswamys/Adobe/download/*.py'
files=glob.glob(path)
for file in files:
    f=open(file, 'r')
    f.readlines()
    f.close()