dwb
dwb

Reputation: 483

Unable to find string in text file

I am trying to simple find if a string exists in a text file, but I am having issues. I am assuming its something on the incorrect line, but I am boggled.

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)

Output:

File Not Found
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\Test1.zip
File Not Found
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\test2.zip

Text within the history.db file:

C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\Test1.zip
C:\Users\jefhill\Desktop\Python Stuff\Projects\autoExtract\test2.zip

What am I missing? Thanks in advance

Note: cFile is the file path shown in the output and fileList is the list of both the paths from the output.

Upvotes: 1

Views: 206

Answers (2)

Michael
Michael

Reputation: 2414

You're using the wrong flags for what you want to do. open(file, 'a') opens a file for append-writing, meaning that it seeks to the end of the file. Adding the + modifier means that you can also read from the file, but you're doing so from the end of the file; so read() returns nothing, because there's nothing beyond the end of the file.

You can use r+ to read from the start of the file while having the option of writing to it. But keep in mind that anytime you write you'll be writing to the reader's current position in the file.

Upvotes: 2

TheLazyScripter
TheLazyScripter

Reputation: 2665

I haven't tested the code but this should put you on the right track!

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

Upvotes: 1

Related Questions