【问题标题】:Having trouble trying to add a line to a text file if that line doesn't exist already using Python fileinput.FileInput(...)如果使用 Python fileinput.FileInput(...) 该行不存在,则尝试将行添加到文本文件时遇到问题
【发布时间】:2011-08-30 23:30:20
【问题描述】:

我正在尝试使用 Python FileInput 类编辑文本文件。首先,我将需要写入的行存储在字典中。然后我遍历那个字典,如果字典[key] 匹配该行中的任何行,我用字典键值对替换该行。如果文件中不存在字典[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)

任何意见将不胜感激。

谢谢!

【问题讨论】:

    标签: python writetofile file-io


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2017-05-04
      • 2016-01-26
      相关资源
      最近更新 更多