python - Python3:尝试在两个字符之间插入文本 - inputFile 与 file.write() 冲突
问题描述
我正在尝试将 PHP 关联数组写入文件。
return [
'welcome' => 'Welcome to our application'
];
- 如果文件不存在,我将上面的数组写入文件
- 如果文件已经存在,我在数组内的字符串中添加一个逗号,然后删除,
];
然后添加第二行,然后关闭数组。 - 所有单独的代码片段都在工作,当我把它们放在一起时,我开始遇到问题,有点像竞争条件。
编码
import fileinput
from pathlib import Path
import os
def translateLaravel(filename, expression):
key = "".join([expression[0], filename, "__", expression[1:]])
key = key.replace(" ", "_")
key = key.strip('')
translation_file_path = 'files/Translation.php'
if os.path.isfile(translation_file_path) == False: # the file doesn't exist
string = "".join(['<?php', '\n', 'return [', '\n', key, ' => ', expression, '\n', '];'])
with open(translation_file_path, 'w') as the_file:
the_file.write(string)
else:
with fileinput.FileInput(os.path.abspath(translation_file_path), inplace=True) as file:
for line in file:
if '=>' in line:
line = line.rstrip()
if not line.endswith(','):
print(line.replace(line, ''.join([line, ',', '\n'])))
elif '];' in line:
print(line.replace(line,''))
with open(translation_file_path, 'a') as the_file:
the_file.write(''.join([key, ' => ', expression, '\n', '];']))
return key
发生了什么:
if os.path.isfile(translation_file_path)
返回 false 并执行代码,但它不会向文件写入任何内容- 如果我删除 else 条件,那么前者会再次开始工作而没有任何问题。
因此,我怀疑 file.write() 没有足够的时间写入文件,但显然我错了,因为我试图sleep(1)
提供file.write()
足够的时间,但这并没有解决问题。
解决方案
推荐阅读
- ruby-on-rails - 如何创建自引用模型
- reactjs - React Context - 上下文和子渲染没有更新
- java - 如何将字节转换为显示其十六进制值的字符串(0x0e ->“0E”)
- python - 没有标记就不能清理网络爬虫吗?用正则表达式是不是不能让它干净?
- python - 在 python 中使用 np.r_ 和 np.c_ VS hstack 和 vstack。在使用两者时给出相同的输出
- python - 如何在 keras 中进行自定义回调以在 VAE 训练中生成示例图像?
- python - 如何使用不同版本的 Python 运行 Jupyter Notebook?
- java - 使用 Floyd 算法在字符串矩阵中显示最短路径
- angular - Angular rxjs 过滤器可观察
- bootstrap-4 - 可滚动的引导列