我想将python变量结果保存到文件中

时间:2016-11-09 06:25:36

标签: python file

运行此文件时,

将相应的输出值显示为;

# 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

等......然后将这些值存储在文本文件中。对于文本文件,是否可以生成文本文件作为脚本的一部分?感谢

2 个答案:

答案 0 :(得分: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()

编辑:现在附加模式

答案 1 :(得分: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)