我正在练习该os
模块,更具体地说os.walk()
。我想知道是否有一种更简单/更有效的方法来查找文件的实际路径,考虑到这会产生一个表明文件在os.walk()
第一次运行时位于原始文件夹中的路径:
import os
threshold_size = 500
for folder, subfolders, files in os.walk(os.getcwd()):
for file in files:
filePath = os.path.abspath(file)
if os.path.getsize(filePath) >= threshold_size:
print filePath, str(os.path.getsize(filePath))+"kB"
这是我目前的解决方法:
import os
threshold_size = 500
for folder, subfolders, files in os.walk(os.getcwd()):
path = os.path.abspath(folder)
for file in files:
filePath = path + "\\" + file
if os.path.getsize(filePath) >= threshold_size:
print filePath, str(os.path.getsize(filePath))+"kB"
对于 shaktimaan,这是:
for folder, subfolders, files in os.walk(os.getcwd()):
for file in files:
filePath = os.path.abspath(file)
print filePath
产生这个(这些文件中的大多数都在项目的子文件夹中,而不是项目本身):
C:\Python27\projects\ps4.py
C:\Python27\projects\ps4_encryption_sol.py
C:\Python27\projects\ps4_recursion_sol.py
C:\Python27\projects\words.txt
C:\Python27\projects\feedparser.py
C:\Python27\projects\feedparser.pyc
C:\Python27\projects\news_gui.py
C:\Python27\projects\news_gui.pyc
C:\Python27\projects\project_util.py
C:\Python27\projects\project_util.pyc
C:\Python27\projects\ps5.py
C:\Python27\projects\ps5.pyc
C:\Python27\projects\ps5_test.py
C:\Python27\projects\test.py
C:\Python27\projects\triggers.txt
C:\Python27\projects\ps6.py
C:\Python27\projects\ps6_pkgtest.py
C:\Python27\projects\ps6_solution.py
C:\Python27\projects\ps6_visualize.py
C:\Python27\projects\ps6_visualize.pyc
C:\Python27\projects\capitalsquiz1.txt
C:\Python27\projects\capitalsquiz2.txt
C:\Python27\projects\capitalsquiz3.txt
C:\Python27\projects\capitalsquiz4.txt
C:\Python27\projects\capitalsquiz5.txt
C:\Python27\projects\capitalsquiz_answers1.txt
C:\Python27\projects\capitalsquiz_answers2.txt
C:\Python27\projects\capitalsquiz_answers3.txt
C:\Python27\projects\capitalsquiz_answers4.txt
C:\Python27\projects\capitalsquiz_answers5.txt
C:\Python27\projects\quiz.py
C:\Python27\projects\file2.txt
C:\Python27\projects\regexes.txt
C:\Python27\projects\regexsearch.py
C:\Python27\projects\testfile.txt
C:\Python27\projects\renamedates.py