파이썬

txt 파일에 데이터 열어서 그래프 그리기

쭤린이 2021. 7. 4. 03:13

1. dialog로부터 파일 경로 받아오기

 

###########################################################

import tkinter as tk

from tkinter import filedialog

 

root = tk.Tk()

root.withdraw()

 

file_path = filedialog.askopenfilename()

 

print('파일경로:'file_path)

###########################################################

 

파일경로 출력

2. 경로에서 데이터 불러오기

 

###########################################################

import numpy as np

import matplotlib.pyplot as plt

 

file = open(file_path'r'encoding = 'utf-8')

f = file.read()

file.close() # 인터넷보면 닫아야된다는 주장도 있고 아닌 주장도 있고.....

 

channel_names = f[int(f.find('[column names]')+len('[column names]\n')):int(f.find('[data]'))-2]

# column names에 있는 체널만 따오기 위해서 잘라냄

channel_names = channel_names.split(' ')

# split으로 나누어서 list 만들어 나중에 time, velocity와 같은 channel에 넣기위해 list로 만듬

###########################################################

 

3. 데이터 플롯하기

###########################################################

data = f[(int(f.find('[data]')))+len('[data]\n'):]

f = open('data.txt''w')

f.write(data)

f.close()

# 현재 데이터를 바로 긁어와서 구분하는 방법을 몰라서 txt로 만든다음 불러서 다시 데이터 나눔

 

data = np.loadtxt('data.txt')

time = data[:, channel_names.index('time')]

velocity = data[:, channel_names.index('velocity')]

 

plt.plot(timevelocity)

plt.show()

###########################################################

 

4. 결과

결과 플롯

 

6. 전체 코딩

 

######### dialog로부터 선택된 파일경로 받아오기 #############

import tkinter as tk

from tkinter import filedialog

 

root = tk.Tk()

root.withdraw()

 

file_path = filedialog.askopenfilename()

 

print('파일경로:'file_path)

###########################################################

 

import numpy as np

import matplotlib.pyplot as plt

 

file = open(file_path'r'encoding = 'utf-8')

f = file.read()

file.close() # 인터넷보면 닫아야된다는 주장도 있고 아닌 주장도 있고.....

 

channel_names = f[int(f.find('[column names]')+len('[column names]\n')):int(f.find('[data]'))-2]

# vbo파일에 column names에 있는 체널만 따오기 위해서 잘라냄

channel_names = channel_names.split(' ')

# split으로 나누어서 list 만들어 나중에 time, velocity와 같은 channel에 넣기위해 list로 만듬

 

data = f[(int(f.find('[data]')))+len('[data]\n'):]

f = open('data.txt''w')

f.write(data)

f.close()

# 현재 데이터를 바로 긁어와서 구분하는 방법을 몰라서 txt로 만든다음 불러서 다시 데이터 나눔

 

data = np.loadtxt('data.txt')

time = data[:, channel_names.index('time')]

velocity = data[:, channel_names.index('velocity')]

 

plt.plot(timevelocity)

plt.show()