开发者

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

开发者 https://www.devze.com 2023-04-01 21:50 出处:网络
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

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. 开发者_StackOverflow

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
0

精彩评论

暂无评论...
验证码 换一张
取 消