2016-11-09 77 views
1

當這個文件運行時給出相應的輸出值爲;我想將python變量結果保存到文件

# test BLE Scanning software 
# jcs 6/8/2014 


import MySQLdb as my 
import blescan 
import sys 


import bluetooth._bluetooth as bluez 

dev_id = 0 

db = my.connect(host="localhost", 
user="root", 
passwd="root", 
db="test" 
) 

cursor = db.cursor() 

try: 
    sock = bluez.hci_open_dev(dev_id) 
    print "ble thread started" 

except: 
    print "error accessing bluetooth device..." 
     sys.exit(1) 

blescan.hci_le_set_scan_parameters(sock) 
blescan.hci_enable_le_scan(sock) 




while True: 
    returnedList = blescan.parse_events(sock, 10) 
    print "----------" 
    for beacon in returnedList: 

     print beacon 


sql = "insert into beacon VALUES(null, '%s')" % \ 
(beacon) 

number_of_rows = cursor.execute(sql) 
db.commit() 

db.close() 

我想存儲在一個文本文件中

cf:68:cc:c7:33:10,b9407f30f5f8466eaff925556b57fe6d,13072,52423,-74,-78 
cf:68:cc:c7:33:10,74696d6f74650e160a181033c7cc68cf,46608,13255,-52,-77 
da:f4:2e:a0:70:b1,b9407f30f5f8466eaff925556b57fe6d,28849,11936,-74,-79 
da:f4:2e:a0:70:b1,74696d6f74650e160a18b170a02ef4da,46769,28832,46,-78 
dd:5d:d3:35:09:dd,8aefb0316c32486f825be26fa193487d,1,1,-64,-78 
c3:11:48:9b:cf:fa,8aefb0316c32486f825be26fa193487d,0,0,-64,-73 
fd:5b:12:7f:02:e4,b9407f30f5f8466eaff925556b57fe6d,740,4735,-74,-79 
fd:5b:12:7f:02:e4,74696d6f74650e160a18e4027f125bfd,46820,639,18,-80 
dd:5d:d3:35:09:dd,8aefb0316c32486f825be26fa193487d,1,1,-64,-77 

等輸出......然後寫在文本文件中的這些值存儲。對於文本文件,是否可以生成文本文件作爲腳本的一部分?由於

+0

[是!](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-文件)你的燈塔是一個簡單的列表嗎? –

+0

是,我想保存 iBeacon顯示MAC地址 iBeacon顯示UDID iBeacon顯示主編號 iBeacon顯示次編號 發射功率1個處 結果到MySQL數據庫 – shane

回答

0

試試這個爲你的循環

while True: 
    returnedList = blescan.parse_events(sock, 10) 
    print "----------" 
    f = open('bluez.txt', 'a+') 
    for beacon in returnedList: 
     print beacon 
     f.write(','.join(beacon)+'\n') 
    f.close() 

編輯:現在追加模式

+0

您確定要覆蓋該文件每通過while循環的時間? –

+0

雖然不會覆蓋,但我想附加結果 – shane

+0

是否可以將這些值保存在mysql數據庫表中? – shane

0

,如果你想要的是將數據存儲在文件中,這樣你就可以打開它後,最簡單的方法是使用在Pickle(或cPickle)模塊 類似:

import cPickle 

#store the data in file 

with open('/path/to/file.txt', 'wb') as f: 
    cPickle.dump(returnedList, f) 

#to read the data 

loaded_returnedList = cPickle.load(open('/path/to/file.txt')) 

print loaded_returnedList == returnedList # Prints True 

現在如果你想要的是存儲可視化存儲中的數據(可是在Excel中後打開它),在csv模塊是你

import csv 

with open('/path/to/file', 'w') as f: 
    writer = csv.writer(f) 

    for beacon in returnedList: 
     writer.writerow(beacon) 
+0

它給了我一個作家= csv.writer(f)預計一個縮進塊 – shane

+0

你可能應付它沒有4空格在開始。記住在python縮進中它非常重要。 – aleivag

相關問題