猿问

os.scandir() 在循环中为 find() 创建问题

我尝试在从 os.scandir() 派生的文件名中找到一个字符串,就像 'ilikecake15.pdf' 或 'ilike1615cake.pdf' 中的字符串 '15' 字符串是唯一的。此代码的背景:我有几个文件夹,其中包含需要与列表匹配的 pdf。文件名包含列表中的部分字符串。我认为使用 for 循环可以解决问题,从 txt 中获取信息。另一个来自 os.scandir() 和 find() 检查 != -1。


故障排除给我留下了两个 .txt 的值,我尝试将它们与 s.find(ins) 进行比较。我的目标是整理出 != -1。如果我定义 v1 和 v2 并执行 v1.find(v2) 似乎可以工作,但是在嵌套的 for 循环中,一切都显示为 -1。(即使我看到正确的匹配)我已经使用 [xx] 从文本文件中删除了路径信息,如 G:\thispath\and\thispath。甚至尝试将 str() 添加到几乎所有内容中(以防万一)


import os

tdpath = 'G:\Somepathwithalotofpdfs'

tdfiles = 'G:\Anothersuitablepath/tdfiles.txt'

tdlines = 'G:\Anothersuitablepath/tdlines.txt'

with os.scandir(tdpath) as pth, open(tdfiles, 'w') as fls:

    for td in pth:

        if td.is_file():

            fls.write(str(os.fsdecode(td)[51:])) #str and [51:] added to help troubleshoot

            fls.write('\n')


with open(tdlines) as fp, open(tdfiles) as fls:

    for cnt, line in enumerate(fp):

        for cmt, lajn in enumerate(fls):

            print(lajn, line) #just troubleshooting

            print(str(lajn).find(str(line))) #just troubleshooting

            if lajn.find(line) != -1:

                print('KASWSOFJIDFHAIFHSIHFIAHS') # Hlep ples

在试图排除故障时,这已经变成了一个怪物。但是预期的结果是当它从 tdfiles.txt 中的文件 tdlines.txt 找到匹配项时打印后一条语句


陪伴而非守候
浏览 249回答 1
1回答
随时随地看视频慕课网APP

相关分类

Python
我要回答