確保您瞭解os.walk
三個返回值:
for root, subdirs, files in os.walk(rootdir):
具有以下含義:
root
:「走過」的當前路徑
subdirs
:文件中的目錄類型
files
的root
:文件中的目錄相比
並請使用os.path.join
,而不是用斜槓串聯的其他類型的root
(不subdirs
)!您的問題是filePath = rootdir + '/' + file
- 您必須連接當前「走」的文件夾而不是最頂層的文件夾。所以那一定是filePath = os.path.join(root, file)
。順便說一句「文件」是一個內置的,所以你通常不使用它作爲變量名稱。
的另一個問題是你的循環,這應該是這樣的,例如:
import os
import sys
walk_dir = sys.argv[1]
print('walk_dir = ' + walk_dir)
# If your current working directory may change during script execution, it's recommended to
# immediately convert program arguments to an absolute path. Then the variable root below will
# be an absolute path as well. Example:
# walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))
for root, subdirs, files in os.walk(walk_dir):
print('--\nroot = ' + root)
list_file_path = os.path.join(root, 'my-directory-list.txt')
print('list_file_path = ' + list_file_path)
with open(list_file_path, 'wb') as list_file:
for subdir in subdirs:
print('\t- subdirectory ' + subdir)
for filename in files:
file_path = os.path.join(root, filename)
print('\t- file %s (full path: %s)' % (filename, file_path))
with open(file_path, 'rb') as f:
f_content = f.read()
list_file.write(('The file %s contains:\n' % filename).encode('utf-8'))
list_file.write(f_content)
list_file.write(b'\n')
如果你不知道,with
聲明的文件是一個速記:
with open('filename', 'rb') as f:
dosomething()
# is effectively the same as
f = open('filename', 'rb')
try:
dosomething()
finally:
f.close()
一流的大量印刷品,以瞭解發生了什麼,它完美地運作。謝謝! +1 – 2010-02-06 09:52:41
擡起頭給任何人當啞巴/忘記爲我...這個代碼示例一個txt文件寫入到每個目錄。很高興我測試了它在版本控制的文件夾,但我需要的一切寫一個清理腳本也在這裏:) – Steazy 2014-09-24 23:56:33