简体   繁体   中英

Having trouble trying to add a line to a text file if that line doesn't exist already using Python fileinput.FileInput(…)

I'm trying to edit text files using the Python FileInput class. First I store the lines that i need to write in a Dictionary. Then I iterate through that dictionary, and if the dictionary[key] matches any line in that line, I replace the line with the dictionary key-value pair. If the dictionary[key] does not exist in the file, then I want to write that line at the end of the file; however, this last part is not working and is not writing to file.

Here is what the current code looks like:

def file_edit(properties, dst_path):

for key in properties.iterkeys():
    for line in fileinput.FileInput(dst_path, inplace=1):
        if str(key) + '=' in line:                      #<==== This works    
            print key + '=' + properties[key]           #<==== This works
        #The below condition checks that if the Dictionary[Key] is not there, then just print the line
        elif str(key) + '=' not in line and re.findall(r'[a-zA-Z0-9=:]+',line) is not None:
            print line.strip()              #<==== This seems to work
        else:                                      #<============THIS DOES NOT WORK
            print key + '=' + properties[key]      #<============THIS DOES NOT WORK
    fileinput.close()

file_edit( {'new key': 'some value', 'existing key': 'new value'}, SomeTextFile.TXT)

Any inputs would be much appreciated.

Thanks!

re.findall() will never return None, if there are no matches it will return an empty list. Because of this your first elif will always be true. You should be using re.search() instead (since you aren't using the result of findall() anyway):

>>> re.findall(r'[a-zA-Z0-9=:]+', "(>'_')>")
[]
>>> re.findall(r'[a-zA-Z0-9=:]+', "(>'_')>") is not None
True
>>> re.search(r'[a-zA-Z0-9=:]+', "(>'_')>")
None
>>> re.search(r'[a-zA-Z0-9=:]+', "(>'_')>") is not None
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM