python - 在文本文件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 文件可能不会很大,因此希望这不会引起问题。
解决方案
我重构了你的代码,虽然我不确定如何命名一些变量。
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)
推荐阅读
- android-espresso - 测试 2 个应用程序之间的通知
- validation - 如何在环回 3 非持久模型中验证自定义休息端点?
- python - Jupyter 笔记本中的 Imagegrid
- android - Android API 和 Gradle 版本
- python - 出现错误:ValueError:要解包的值太多(预期为 5)
- android-studio - 在新版本的android studio(3.2)中,如何获取apk文件?
- ios - 我可以在 Objective-C 中为我自己的弃用添加 fix-it 吗?
- css - (Angular 6)动态地将样式添加到单击的元素中。旋转人字形
- php - 如何说服 Zend Framework 发送重复的标头?
- powerbi - M 公式将缺失的日期添加到表中