对于Python中的while循环循环创建多个文件并用数据覆盖它们?

时间:2017-05-18 15:34:16

标签: python for-loop tkinter while-loop

所以,我目前有一个没有错误运行的代码(耶!)。

但是,串行数据只写入两个文本文件。 (serial0.txt和serial1.txt)。我想让它一直运行(我有一个暂停按钮),最多可以创建11个文件,在每个文件中放置/读取数据,然后在while循环重新开始时覆盖相同的11个文本文件。

背景:这是很多数据。我想在暂停看之后拉出一个文本文件;但截至目前,我不希望保留我正在创建的所有数据文件。因此,只创建了几个文本文件。

代码:(我只粘贴了我认为相关的内容,但如果需要我会粘贴更多内容)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

ser.stopbits = 2
  #pack actually displays it in the window


def get_data():

    namerange = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
    while True:

        for i in namerange:

            f = open("serial" + str(i) + ".txt", 'w+')             
            #f = open("serial%d.txt") % i
            data=ser.readline()
            f.write(str(data))
            f.close()


            lines = open("serial" + str(i) + ".txt", 'r+')

            read_serial=lines.readline()

            mylist = [int(x) for x in read_serial.split(',') if x.strip().isdigit()]
            x = np.linspace(340, 850, num=len(mylist))
            ax1.clear()
            lines.close()
            ax1.plot(x, mylist)
            plt.ylim([0, 1000])
            return x, mylist

1 个答案:

答案 0 :(得分:0)

以防万一将来有人想知道这件事,这就是我最终做的事情,而且工作正常!

from tkinter import *
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk
from PIL import ImageTk, Image
import time
import io
import serial
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import numpy as np
import sys
import random
from threading import Thread

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) #define data incoming     from the serial port

ser.stopbits = 2
  #pack actually displays it in the window


def samples():

    namerange = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    for i in namerange:
        print (i)    
        f = open("serial" + str(i) + ".txt", 'w+')#encoding='utf-8')              
        #f = open("serial%d.txt") % (i)
        data=ser.readline() #read the defined serial import
        f.write(str(data)) #place data into the text file
        f.close() #close the text file


        lines = open("serial" + str(i) + ".txt", 'r+')#, encoding='utf-8')      #open that same text file (reading priviledges)

        read_serial=lines.readline() #read the text file
        global mylist
        mylist = [int(x) for x in read_serial.split(',') if x.strip().isdigit()] #make the read data an interger and strip it of any data     that is not a number (comma, ending/beginning letters)
        global x
        x = np.linspace(340, 850, num=len(mylist)) #creation of x axis
        ax1.clear()
        lines.close() #close the text file
        ax1.plot(x, mylist)
        plt.ylim([0, 1000])
    return x, mylist

def f():
    while True: samples()
    Thread(target=f).start()


Thread(target=f).start()


def get_data():
    global mylist
    global x
    return x, mylist # put it on the graph   

然后,我的图形“开始”按钮只调用“get_data”函数。所以,线程在后台运行,但是当我点击按钮时,我只看到它在图表上的输出。我认为这是一个非常圆的,混乱的方式,但我对此感到满意。