请原谅我,如果这是一个非常简单的问题,但我是 python 新手,我有两个文件路径列表,我想从第一个列表中选择第一个文件,检查具有第一个文件的子字符串的文件,然后运行我的代码。
例如:
第一个列表:
第二个列表
我试过了
if os.path.basename(first_file) in os.path.basename(second_file):
file2 = this_file
open(this_file,'r') as f:
#then run my code
尝试去掉文件扩展名,看看它是否有效,假设这些不是文件的真实名称。如果您要搜索的子字符串不在文件名的末尾,则比较将因扩展名而失败。例如:
"name1.csv" in "testname1.csv" # True
"test.csv" in "testname1.csv" # False
第一个示例有效,因为 name1.csv 在 testname1.csv 中,但第二个失败,因为文件扩展名。
最简单的解决方法是通过切掉最后 4 个字符来删除扩展名,即:
my_search_string = os.path.basename(first_file)
if my_search_string[:-4] in os.path.basename(second_file):
[:-4]
从字符串末尾向后计数 4 个字符并返回其他所有字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句