因此,我正在编写一个cli工具,该工具接收一个文件并计算该文件的校验和(CRC32)。我希望我的工具可以选择递归。所以我想要目录中所有文件的列表,以便可以将其作为参数传递给我的校验和方法。
注意:“ Test Dir /”是与脚本位于同一文件夹中的目录,并且是通过终端而不是设置变量输入的。
到目前为止,我有:
rootDir = ['Test Dir/']
files = []
for i in rootDir:
if not os.path.isdir(i):
files.append(i)
else:
for dir_, _, files in os.walk(i):
for fileName in files:
relDir = os.path.relpath(dir_, i)
relFile = os.path.join(relDir, fileName)
files.append(relFile)
返回:
['./root.py', './root.txt', 'Lv1/lv1.py', 'Lv1/lv1.pyc', 'Lv1/lv1.txt', 'Lv1/Lv2/lv2.pyc', 'Lv1/Lv2/lv2.py', 'Lv1/Lv2/lv2.txt', 'Lv1/Lv2/Lv3/lv3.txt', 'Lv1/Lv2/Lv3/lv3.py', 'Lv1/Lv2/Lv3/lv3.pyc']
但是如果我输入rootDir作为'Test Dir / *',我得到:
['./lv1.py', './lv1.pyc', './lv1.txt', 'Lv2/lv2.pyc', 'Lv2/lv2.py', 'Lv2/lv2.txt', 'Lv2/Lv3/lv3.txt', 'Lv2/Lv3/lv3.py', 'Lv2/Lv3/lv3.pyc', 'Test Dir/root.py', 'Test Dir/root.txt']
相同的文件,但列表稍有不同。
我想要的是:['Test Dir/root.py', 'Test Dir/root.txt', 'Test Dir/Lv1/lv1.py', 'Test Dir/Lv1/lv1.pyc', 'Test Dir/Lv1/lv1.txt', 'Test Dir/Lv1/Lv2/lv2.pyc', 'Test Dir/Lv1/Lv2/lv2.py', 'Test Dir/Lv1/Lv2/lv2.txt', 'Test Dir/Lv1/Lv2/Lv3/lv3.txt', 'Test Dir/Lv1/Lv2/Lv3/lv3.py', 'Test Dir/Lv1/Lv2/Lv3/lv3.pyc']
现在我知道我可以使用字符串操作来做到这一点,但这似乎并不干净……真希望有人可以对此提供帮助。
解决方案
os.path.relpath起作用的方式是,它仅包括给定基本路径下的路径名,因此,如果您希望最终列表中的所有路径都包括基本路径名,则实际上您无需os.path.relpath开头。
同样,files用于for循环的变量会遮盖files您在开始时初始化并在for循环内使用的列表。您的代码实际上不会完成,因为您在将其用作迭代器时不断追加到列表中。您应该给它起别的名字。
您的代码应更正为:
rootDir = ['Test Dir/']
paths = []
for i in rootDir:
if not os.path.isdir(i):
paths.append(i)
else:
for dir_, _, files in os.walk(i):
for fileName in files:
paths.append(os.path.join(i, fileName))