我在下面嘗試了幾種不同的方法,但遇到了問題 a) 洗掉寬度和 b) 用逗號洗掉 \n。我有一個像下面這樣的txt檔案,我想獲取該資訊并在sqlite中創建一個表(全部使用python)
"field",width, type
name, 15, string
revenue, 10, decimal
invoice_date, 10, string
amount, 2, integer
當前的 python 代碼 - 嘗試讀取檔案,并獲取要在下面的 sql 陳述句中傳遞的值
匯入 os 匯入熊貓作為 pd
dir_path = os.path.dirname(os.path.realpath(__file__))
file = open(str(dir_path) '/revenue/revenue_table_specifications.txt','r')
lines = file.readlines()
table = lines[2::]
s = ''.join(str(table).split(','))
x = s.replace("\n", ",").strip()
print(x)
我要傳入的sql
c = sqlite3.connect('rev.db') #connnect to DB
try:
c.execute('''CREATE TABLE
revenue_table (information from txt file,
information from txt file,
....)''')
except sqlite3.OperationalError: #i.e. table exists already
pass
uj5u.com熱心網友回復:
這會產生一些有用的東西。
def makesql(filename):
s = []
for row in open(filename):
if row[0] == '"':
continue
parts = row.strip().split(", ")
s.append( f"{parts[0]} {parts[2]}" )
return "CREATE TABLE revenue_table (\n" ",\n".join(s) ");"
sql = makesql( 'x.csv' )
print(sql)
c.execute( sql )
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/401089.html
