gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:01 25 4
gpt4 key购买 nike

我正在尝试使用 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

关于python - 如果使用 Python fileinput.FileInput(...) 不存在该行,则尝试向文本文件添加该行时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7250941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com