【问题标题】:Unable to find string in text file无法在文本文件中找到字符串
【发布时间】: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


【解决方案1】:

您为想要做的事情使用了错误的标志。 open(file, 'a') 打开一个文件以进行追加写入,这意味着它会寻找文件的末尾。添加+ 修饰符意味着您也可以从文件中读取,但您是从文件末尾开始的;所以read() 什么都不返回,因为文件末尾没有任何内容。

您可以使用r+ 从文件开头读取,同时可以选择写入文件。但请记住,任何时候你写你都会写到读者在文件中的当前位置。

【讨论】:

  • 哇,我觉得这很简单。感谢您的帮助!
【解决方案2】:

我还没有测试过代码,但这应该会让你走上正轨!

def extract(mPath, frequency):
    if not os.path.exists('history.db'):
        f = open("history.db", "w+")
        f.close()
    with open('history.db', "rb") as f:
        data = f.readlines()

    for line in data:
        if line.rstrip() in fileList: #assuming fileList is a list of strings
            #do everything else here

【讨论】:

    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多