1. 程式人生 > >python 遍歷目錄下所有檔案

python 遍歷目錄下所有檔案

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
def gci(filepath):
#遍歷filepath下所有檔案,包括子目錄
  files = os.listdir(filepath)
  for fi in files:
    fi_d = os.path.join(filepath,fi)            
    if os.path.isdir(fi_d):
      gci(fi_d)                  
    else:
      print os.path.join(filepath,fi_d)

#遞迴遍歷/root目錄下所有檔案
gci('/root')

Python編寫生成樹狀結構的檔案目錄

# -*- coding:utf-8 -*-
import os
def list_files(startPath):
  fileSave = open('list.txt','w')
  for root, dirs, files in os.walk(startPath):
    level = root.replace(startPath, '').count(os.sep)
    indent = ' ' * 1 * level
    #fileSave.write('{}{}/'.format(indent, os.path.basename(root)) + '\n')
    fileSave.write('{}{}\\'.format(indent, os.path.abspath(root)) + '\n')
    subIndent = ' ' * 1 * (level + 1)
    for f in files:
      #fileSave.write('{}{}'.format(subIndent, f) + '\n')
      fileSave.write('{}{}{}'.format(subIndent, os.path.abspath(root), f) + '\n')
  fileSave.close()
  
dir = raw_input('please input the path:')
list_files(dir)
Python中沒有專門定義結構體的方法,但可以使用class標記定義類來代替結構體,
其成員可以在建構函式__init__中定義,具體方法如下。
class item:
    def __init__(self):
        self.name = ''     # 名稱
        self.size = 10     # 尺寸
        self.list = []     # 列表

a = item() # 定義結構物件 a.name = 'cup' a.size = 8 a.list.append('water')