Version
Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10
System version :Windows 10
分別取得資料夾路徑與檔案路徑
Code:
import os
dir_path = r'E:\download\tmp\test'
# 取得路徑下的檔案名稱與資料夾名稱
dir_list = os.listdir(dir_path)
# 取得路徑下的檔案名稱與完整路徑
only_file=[dir_path+'\\'+name for name in os.listdir(dir_path) if os.path.isfile(dir_path+'\\'+name) ]
# 取得路徑下的資料夾名稱與完整路徑
only_dir=[dir_path+'\\'+name for name in os.listdir(dir_path) if os.path.isdir(dir_path+'\\'+name) ]
# 取的路徑下的 file 名稱
only_file2 = [ele for ele in dir_list if os.path.isfile(os.path.join(dir_path,ele))]
# 取的路徑下的 dir 名稱
only_dir2 = [ele for ele in dir_list if os.path.isdir(os.path.join(dir_path,ele))]
print(dir_list)
print('')
print(only_file)
print(only_dir)
print('')
print(only_file2)
print(only_dir2)
Result:
['dir1', 'dir2', 'file1.txt', 'file2.txt']
['E:\\download\\tmp\\test\\file1.txt', 'E:\\download\\tmp\\test\\file2.txt']
['E:\\download\\tmp\\test\\dir1', 'E:\\download\\tmp\\test\\dir2']
[ 'file1.txt', 'file2.txt']
['dir1', 'dir2']
將深層的檔案路徑加到list中
Code:
import os
dir_path = r'E:\download\tmp2'
file_list=[]
for dirPath, dirNames, fileNames in os.walk(dir_path):
for f in fileNames:
file_list.append(os.path.join(dirPath, f))
print(file_list)
Result:
['E:\\download\\tmp2\\2017\\1\\1\\20170101_1.txt',
'E:\\download\\tmp2\\2017\\1\\1\\20170101_2.txt',
'E:\\download\\tmp2\\2017\\1\\2\\20170102_1.txt',
'E:\\download\\tmp2\\2017\\1\\2\\20170102_2.txt']
沒有留言:
張貼留言