我有一个像这样的字符串:
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)
答案 0 :(得分:0)
尝试此操作,以便保留序列中的最后一个单词:
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
据我从您的代码中了解。
答案 1 :(得分:0)
如果您使用的是Linux环境:
命令: sed -i“如果存在TEST_TABLE,则删除表;” file_path
例如: sed -i“如果存在TEST_TABLE,则删除表;” data.txt
对于Mac:
sed -i'''如果存在TEST_TABLE,则/ DROP TABLE; / d'data.txt
答案 2 :(得分:0)
据我所知,您应该使用正则表达式:
routes
这将删除所有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;
答案 3 :(得分:0)
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 ]
答案 4 :(得分:0)
我建议分开阅读各行,并删除所有以上述语法开头的行。使用此功能,您可以输入文件并更改要删除的语法。但是您当然可以复制逻辑并直接输入文件名。
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