Skip to main content
 首页 » 编程设计

python之如果使用 Python fileinput.FileInput(...) 不存在该行,则尝试向文本文件添加该行时遇到问题

2025年05月04日13jpfss

我正在尝试使用 Python FileInput 类编辑文本文件。首先,我将需要写入的行存储在字典中。然后我遍历该字典,如果字典 [key] 与该行中的任何行匹配,我就用字典键值对替换该行。如果文件中不存在 dictionary[key],那么我想将该行写在文件末尾;但是,这最后一部分不起作用并且没有写入文件。

这是当前代码的样子:

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)

如有任何意见,我们将不胜感激。

谢谢!

请您参考如下方法:

re.findall() 永远不会返回 None,如果没有匹配项,它将返回一个空列表。因此,您的第一个 elif 将始终为真。您应该改用 re.search()(因为无论如何您都没有使用 findall() 的结果):

>>> 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