我试图用python重写文件,但似乎无法弄清为什么文件未被覆盖。这是我的代码:
# these are just for this case.
# These variables come from elsewhere but they will evaluate to these when we hit this point.
command = 'RMDir'
current_dir = '$workingDirectory'
# end variables
product_name_1 = "Product 1"
product_name_2 = "Product 2"
product_name_3 = "Product 3"
product_1_instruction = command + ' \"' + current_dir + '\\' + product_name_1 + '\"\n'
product_2_instruction = command + ' \"' + current_dir + '\\' + product_name_2 + '\"\n'
product_3_instruction = command + ' \"' + current_dir + '\\' + product_name_3 + '\"\n'
file_path = f.name
output = []
f.close()
with open(file_path, 'r+') as f:
for line in f:
if product_1_instruction != line \
and product_2_instruction != line \
and product_3_instruction != line:
output.append(line)
f.writelines(output)
在此代码之前,我们用f
编写了一个文件。现在,我试图将其关闭并重新打开以覆盖它,遍历各行,如果某行与我的指令字符串之一匹配,请将其从output
中排除。循环完成后,我想用f
中的行覆盖output
的内容,但是由于某种原因,它没有发生。
我已经验证了我的相等性检查是否正确,并且output
已正确加载了正确的值,但似乎文件本身并未被正确的内容覆盖。
答案 0 :(得分:2)
首先读取文件,然后在写入模式下将其打开以覆盖它:
with open(file_path, 'r') as f:
for line in f:
if product_1_instruction != line \
and product_2_instruction != line \
and product_3_instruction != line:
output.append(line)
with open(file_path, 'w') as f:
f.writelines(output)
请勿对文本/ csv文件使用读/写模式。对于二进制/固定格式的文件更有用。
请注意,列表推导更具Python感,而不是循环:
forbidden = [product_1_instruction,product_2_instruction,product_3_instruction]
output = [line for line in f if line not in forbidden]
(将forbidden
设为set
(如果您有很多产品,它将使查找速度更快)
答案 1 :(得分:0)
简单使用aws rds describe-db-engine-versions --engine='aurora-postgresql'
,它将删除旧文件并创建新文件。
aws rds describe-db-engine-versions --db-parameter-group-family='aurora-postgresql9.6'