Python 讀取文字檔案到sql server

2021-09-29 20:43:58 字數 1424 閱讀 3937

import json

import pymysql

import sqlite3

import re

import pyodbc

import os #載入所需模組

sqlconn=pyodbc.

connect

(driver='',

server=

'伺服器名稱'

,database

='資料庫名稱'

)#連線資料庫

cursor

=sqlconn.

cursor()

#開啟游標

cursor

.execute

("create table hb(\

id varchar(32) not null,\

fnum varchar(32) not null,\

csta varchar(255) not null,\

ccity varchar(32) ,\

dcity varchar(32) ,)\

")#執行sql語句

f =open

('位址\\檔案.txt'

,"r"

,encoding=

'utf-8'

)while

1: lines

= f.readline(

)#按行讀取

ifnot

lines:

break

#當讀取所有行結束迴圈讀取

items =

[i for i in

lines

.split()]

#將每一行存為list

print

(items)

cursor

.execute

("insert into hb(id,fnum,csta,ccity,dcity)values('%s','%s','%s','%s','%s')"

%(items[0]

,items[1]

,items[2]

,items[3]

,items[4]

))#執行sql語句

cursor

.execute

("select * from hb"

)#執行sql語句

queryresult=

cursor

.fetchall(

)#查詢執行的sql操作

print

(queryresult)

sqlconn.

commit()

cursor

.close()

#關閉游標

sqlconn.

close()

#關閉資料庫連線

Python讀取文字檔案到陣列

支援的格式有txt,dat,csv,mat等 讀入的資料存為float型別,可以自定義資料之間的間隔符,可以自定義列數cols import numpy as np import linecache import os filename data.dat cols 12 number of colu...

Python讀取文字檔案

給定c data hello.txt,內容如下 jack hello,how are you?rose i m good.按行讀取 filepath r c data hello.txt with open filepath as txtfile for line in txtfile print ...

讀取文字檔案

void ctestdlg onreadinfo cfile filewrite1 testwrite1.txt cfile modecreate cfile modewrite cfile filewrite2 testwrite2.txt cfile modecreate cfile modew...