我想要实现的是为每个以特定数字开始并以".shp"结束的文件创建列表。一个列表包含所有以1开头以".shp"结尾的文件,另一个列表包含所有以2开头以"等等。
这是我正在使用的代码片段:
from os.path import normpath
import os
path_temp2 = normpath(r'C:\Users\tlind\Dropbox\Documents\Temp\temp2layers\')
merge_list = os.listdir(path_temp2)
for i in range(1,13):
test = []
check = str(i)
res = [idx for idx in merge_list if idx.lower().startswith(check.lower())]
test.append(res)
for file in test:
test2 = []
if file.endswith('.shp'):
test2.append(file)
print(test2)
它返回:AttributeError: 'list'对象没有属性'endswith'
编辑:这几乎解决了这个问题:
from os.path import normpath
import os
path_temp2 = normpath(r'C:\Users\tlind\Dropbox\Documents\Temp\temp2layers\')
merge_list = os.listdir(path_temp2)
for i in range(1,13):
check = str(i)
name_ext_matches = []
name_matches = [idx for idx in merge_list if idx.lower().startswith(check.lower())]
for file in name_matches:
if file.endswith('.shp'):
name_ext_matches.append(file)
print(name_ext_matches)
这个有很大的DOH。第一个列表包括10,11和12。我得想办法解决这个问题。有人有什么建议吗?
list
没有属性endswith
,因为您已将test
作为列表的列表。您应该将当前分配给res
的内容分配给test
,或者您应该迭代res
而不是test
。
现在,test
的值是一个列表,它的第一个也是唯一一个元素是另一个列表,该列表包含所有以i
的字符串值开头的文件。
你可以这样做:
for i in range(1,13):
check = str(i)
# all files starting with the string-value of `i`
name_matches = [idx for idx in merge_list if idx.lower().startswith(check.lower())]
for file in name_matches:
# all files that start with `i` AND end with `.shp`
name_ext_matches = []
if file.endswith('.shp'):
name_ext_matches.append(file)
print(name_ext_matches)
通过在数字末尾添加下划线来解决:
from os.path import normpath
import os
path_temp2 = normpath(r'C:\Users\tlind\Dropbox\Documents\Temp\temp2layers\')
merge_list = os.listdir(path_temp2)
for i in range(1,13):
check = str(i)+'_'
name_ext_matches = []
name_matches = [idx for idx in merge_list if idx.lower().startswith(check.lower())]
for file in name_matches:
if file.endswith('.shp'):
name_ext_matches.append(file)
print(name_ext_matches)