【发布时间】:2019-09-06 00:38:40
【问题描述】:
我正在尝试简单地查找文本文件中是否存在字符串,但我遇到了问题。我假设它在不正确的行上,但我很困惑。
def extract(mPath, frequency):
if not os.path.exists('history.db'):
f = open("history.db", "w+")
f.close()
for cFile in fileList:
with open('history.db', "a+") as f:
if cFile in f.read():
print("File found - skip")
else:
#with ZipFile(cFile, 'r') as zip_ref:
#zip_ref.extractall(mPath)
print("File Not Found")
f.writelines(cFile + "\n")
print(cFile)
输出:
找不到文件
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\Test1.zip
找不到文件
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\test2.zip
history.db 文件中的文本:
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\Test1.zip
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\test2.zip
我错过了什么?提前致谢
注意:cFile 是输出中显示的文件路径,fileList 是输出中两个路径的列表。
【问题讨论】:
-
频率应该做什么?还有 mPath?
-
@RichardKeene 目前什么都没有,只是一个占位符。
-
如果
in运算符未能正确报告子字符串的存在,我会感到惊讶。更有可能的是,您对这些字符串的期望与这些字符串的实际含义之间存在冲突。 -
不确定您要做什么... def extract(mPath, frequency): 此行不执行任何操作,因为未使用参数。 if not os.path.exists('history.db'): 为什么只创建空文件然后打开它? f = open("history.db", "w+") f.close() for cFile in fileList: fileList 是在哪里创建的? with open('history.db', "a+") as f: etc....
-
@JohnColeman 我相信你是对的。最好使用
.readlines()而不是.read()并循环遍历每一行,将其与您的控件进行比较。使用rstrip确保每行末尾没有转义符或空格。
标签: python python-3.x