基于某些条件向specidifc位置添加字符串(行)(在Python中)

2024-10-03 00:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下.sql文件:

execute_all.log
set echo on
SET SQLBLANKLINES ON
@@2019-03-26_DX_1.sql
@@2019-05-10_DX_2.sql
@@2019-05-10_DX_3.sql
@@2019-05-14_1600_DX_4.sql
@@2019-05-21_0900_DX_5.sql
@@2019-05-21_0900_DX_6.sql
@@2019-05-21_0900_DX_7.sql
@@2019-05-21_0900_DX_8.sql
SET SQLBLANKLINES OFF
spool off;
@@make_constraint.sql

从“@@”开始的所有内容都是与我相关的文件名。 在列表中,我还有以下文件:

skripts_to_deploy = ['2019-05-14_1600_DX_4.sql','2019-05-15_1500_DX_55.sql']

标准如下:

  • 如果文件已经存在,则跳过该文件
  • 如果文件不存在,则遍历files行。如果skripts_to_deploy中文件的日期(在@之后的部分)小于下一行中的日期,则将该行(文件名)添加到此位置(并保留其他行,但如果需要,可以移动)。你知道吗

代码如下:

path = "C:\\Users\\danyef"
skripts_to_deploy = ['2019-05-14_1600_DX_13.sql','2019-05-15_1500_DX_55.sql']    
level = 'DXIDS'
with open(level + "_EXECUTE_ALL.sql","r+") as file:
    for line in file:
        if line == "execute_all.log\n" or line == "set echo on\n" or line == "SET SQLBLANKLINES ON\n":
            continue
        for skript in skripts_to_deploy:
            if '@@' + skript in line:
                continue
            next_line = next(file)
            print(next_line)
            if next_line == 'SET SQLBLANKLINES OFF':
                file.write('@@' + skript + '\n')
                print("written SET SQLBLANKLINES OFF:",skript)
            else:
                next_line = datetime.strptime((next_line.split('_')[0]).split('@@')[1],'%Y-%m-%d')
                if datetime.strptime(skript.split('_')[0],'%Y-%m-%d')<= next_line:
                    file.write('@@' + skript + '\n')
                    print("written:",skript)

重要提示:next_line = datetime.strptime((next_line.split('_')[0]).split('@@')[1],'%Y-%m-%d')只是从现有文件的行中提取日期。你知道吗

在我的代码中,它添加了一行,但是不是在正确的位置(基于上面提到的标准)而是在文件的末尾添加。你知道吗

也许我这边的人漏了,欢迎你改正。 提前谢谢你。你知道吗

编辑:预期输出:

execute_all.log
set echo on
SET SQLBLANKLINES ON
@@2019-03-26_DX_1.sql
@@2019-05-10_DX_2.sql
@@2019-05-10_DX_3.sql
@@2019-05-14_1600_DX_4.sql
**@@2019-05-15_1500_DX_55.sql**
@@2019-05-21_0900_DX_5.sql
@@2019-05-21_0900_DX_6.sql
@@2019-05-21_0900_DX_7.sql
@@2019-05-21_0900_DX_8.sql
SET SQLBLANKLINES OFF
spool off;
@@make_constraint.sql

Tags: 文件tosqliflinedeployfilenext
1条回答
网友
1楼 · 发布于 2024-10-03 00:17:43

大多数文件系统不支持就地插入数据。你知道吗

通常,您有3个选项:

  1. 使用file_obj.seek()(仅用于替换数据)
  2. 加载内存中的所有文件并将其转储回
  3. 创建一个临时文件,在运行时对其进行修改,然后将其复制回原点

选项1似乎已下架,因为您希望插入数据。 选项2似乎最适合您的情况,您只需要相应地调整代码(例如,使用字符串切片和串联,而不是read()write())。 方案3也可以,但一般来说负担更重。但是,如果无法在内存中容纳整个文件,则它特别有用。你知道吗

为了完整起见,下面是每个选项的代码草图。你知道吗


选项1:

# file should be open as a binary to avoid messy offsets due to encoding
with open(filepath, 'rb+') as file_obj: 
    while True:
        line = file_obj.readline()
        if not line:  # reached end-of-file
            break
        if condition(line):  # for strings, use `line.decode()`
            position = file_obj.tell()
            offset = 0  # the offset from the beginning of the line
            file_obj.seek(position - len(line) + offset)  
            # new data must be `bytes`, for strings, use `new_data.encode()`
            file_obj.write(new_data)
            file_obj.seek(position)

选项2:

with open(filepath, 'r+') as file_obj:
    text = file_obj.read()  # read the whole file
    ...                     # do your preprocessing on the text as string
    file_obj.seek(0)        # go back at the beginning of the file
    file_obj.truncate()     # disregard previous content
    file_obj.write(text)    # write data back

选项3:

import shutil

with open(in_filepath, 'r') as in_file_obj, \
        open(out_filepath, 'w') as out_file_obj:
    for line in in_file_obj:
        # should actually reflect your logic here
        if must_insert_here():  
            # preprocess data to insert
            out_file_obj.write(new_line + '\n')

        # should actually reflect your logic here 
        if must_be_present_in_new():  
            out_file_obj.write(line)

# perhaps you actually want to use `copy2()` instead of `copy()`  
shutil.copy(out_filepath, in_filepath)      

相关问题 更多 >