首页 > 解决方案 > 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

发生了什么:

因此,我怀疑 file.write() 没有足够的时间写入文件,但显然我错了,因为我试图sleep(1)提供file.write()足够的时间,但这并没有解决问题。

标签: pythonpython-3.x

解决方案


推荐阅读