【发布时间】:2019-07-27 19:34:12
【问题描述】:
我的任务是创建一个列表列表,其中包含我的 search_dir 文件夹中所有 sql 文件的相对和绝对路径。
问题是我无法事先知道我的主列表应该包含多少个文件(列表)。
有什么方法可以在运行时追加列表吗?
cnt_of_sql_files = 0
for dirpath, subdirs, files in walk(search_dir):
for file in files:
if file.endswith('.sql'):
cnt_of_sql_files +=1
scripts = [[]] * cnt_of_sql_files
for dirpath, subdirs, files in walk(search_dir):
for file in files:
if file.endswith('.sql'):
for index in range(cnt_of_sql_files):
scripts[index] = [path.join(dirpath, file),
path.join(path.basename(dirpath), file)]
print(scripts)
【问题讨论】:
-
...是的,您使用
.append方法。 -
所以,只需使用
scripts = [],然后在您的循环中执行scripts.append([path.join(dirpath, file), path.join(path.basename(dirpath), file)]。 -
您的最终样本输出是什么?