簡體   English   中英

如何刪除python文件中所有帶有未知單詞的行?

[英]How to delete all line with some unknown words in file on python?

我有一個像這樣的字符串:

DROP TABLE IF EXISTS TEST_TABLE;

我需要通過刪除具有上述語法的所有字符串來修改和復制sql-file 假設表的名稱可能會更改,並且在其他行中可能會有所不同。 如何僅知道語法就刪除該行?

with open(r"D:\testfolder\input.sql", 'r') as file_in:
    text = file_in.read()
    text = text.replace("DROP TABLE IF EXISTS ", "")
with open(r"D:\testfolder\t2.sql", 'w') as file_out:
    file_out.write(text)

嘗試此操作,因為您想保留序列中的最后一個單詞:

with open(r"D:\testfolder\t2.sql", 'w') as file_out:
    with open(r"D:\testfolder\input.sql", 'r') as file_in:
        text = file_in.read()
        arr = text.split()[-1]
        file_out.write(arr)

新列表(arr)包括除最后一個單詞以外的所有單詞。 例:

text = 'DROP TABLE IF EXISTS TEST_TABLE'
arr = text.split()[-1]
print arr

得到:

TEST_TABLE

據我從您的代碼了解。

如果您使用的是Linux環境:

命令:sed -i“如果存在測試表,則刪除表;” 文件路徑

例如:sed -i“如果存在TEST_TABLE,則刪除表;” data.txt中

對於Mac:

sed -i'''/如果存在TEST_TABLE,則刪除表; / d'data.txt

據我所知,您應該使用正則表達式:

import re

str = "DROP TABLE IF EXISTS table_name; OTHER STUFF OTHER STUFF OTHER STUFF";

result = re.sub(r'DROP TABLE IF EXISTS .*\;', '', str); # Use this instead of replace()
print(result);

DROP TABLE IF EXISTS any_table_name_here;將刪除所有DROP TABLE IF EXISTS any_table_name_here; 並輸出:

 OTHER STUFF OTHER STUFF OTHER STUFF
import re

#### file 'infopanel.ver' is for example only !
## lines_list = ['Info-Panel V1.2\n', 'Machinebrand: Vu+ \n', 'Machinename: Solo SE \n', 'oem name: vuplus \n', 'Boxtype: vusolose \n', 'Keymap: /usr/share/enigma2/keymap.xml \n']
## lines_str = 'Info-Panel V1.2\nMachinebrand: Vu+ \nMachinename: Solo SE \noem name: vuplus \nBoxtype: vusolose \nKeymap: /usr/share/enigma2/keymap.xml \n'

with open('/tmp/infopanel.ver','r') as f:
    lines_str = f.read()
result = re.sub(ur'.*?Machine.*?', '', lines_str)

with open('/tmp/infopanel.ver','r') as f:
    lines_list = f.readlines()
result = [ line for line in lines_list if 'Machine' not in line ]

我建議分開閱讀各行,並刪除所有以上述語法開頭的行。 使用此功能,您可以輸入文件並更改要刪除的語法。 但是您當然可以復制邏輯並直接輸入文件名。

def clear_file(file1, file2, syntax='DROP TABLE IF EXISTS'):
    with open(file1, 'r') as file_in:
        new_lines = [line for line in file_in.readlines() if not line.startswith(syntax)]
    with open(file2, 'w') as file_out:
        file_out.write(''.join(new_lines))

輸入:

#testfile1.sql
DROP TABLE IF EXISTS TEST_TABLE
IT
DROP TABLE IF EXISTS TEST_2_table.table hello world
DROP TABLE IF EXISTS TABLE foo_bar_baz.tablexyz
WORKS

>>> clear_file('testfile1.sql', 'testfile2.sql')

輸出:

#testfile2.sql
IT
WORKS

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM