首页 > 解决方案 > 在文本文件python中查找字符串的问题

问题描述

我有一个 python 程序,它应该在文本文件中搜索 ID。如果文件中不存在 ID,则程序会将其写入文件。

path = "M:\\Program\\files\\"
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]
for x in range(0, len(files)):
    file = files[x]
    file = file.split('`')
    postid = file[0]
    print(postid)
    with open('postid.txt', 'r+') as f:
            if postid in f:
                print('already used')
            else:
                print('not used')
                f.write(postid + '\r')

当它在文件中时,代码总是返回该字符串不在文件中。我尝试了不同的扫描文件的方法,例如使用 for 循环并检查每一行,但它们没有奏效。我觉得我错过了一些小细节,但我找不到我做错了什么。

该文件看起来像

1k2kk
302kk
2ll3d
2ll32
33lld
ect..

编辑:从来没有发现为什么代码不起作用。我尝试了每一个建议,但没有任何效果。最后放弃了直接从文件中读取的尝试,只是让程序将文件转储到一个列表中,并在列表中搜索 ID 而不是文件。我知道这并不理想,但使用该程序时 ID 文件可能不会很大,因此希望这不会引起问题。

标签: python

解决方案


我重构了你的代码,虽然我不确定如何命名一些变量。

for curr_str in files:
    postid = curr_str.split('`')[0]
    print(postid)
    with open('postid.txt', 'a+') as f:
        for line in f:
            line = line.rstrip()
            if postid == line:
                print('found')
                break
        else:
            print('not found')
            f.write(postid)

推荐阅读