从python中的txt文件中提取两列数字并绘制它们

时间:2017-04-20 11:27:24

标签: python pycharm

我需要在PyCharm中对Python提供一些非常基本的帮助。我试图从.txt文件中提取两列数字(但每列中的数字量都会发生变化),然后绘制它们。到目前为止,这是我的代码。

pacient = str(input("Please enter your the name of the pacient: "))
Pname = pacient+'.txt'
print(Pname)
file  = open(Pname,"r")
print (file.read())

# what i need in here is save the first column of the .txt in 't' and the second one in 'v'. 



import matplotlib.pyplot as plt
plt.plot(t, v)
plt.xlabel('time (v)')
plt.ylabel('Velocity (m/s)')
plt.title(pacient+"plot")
plt.savefig("test.png")
plt.show()

2 个答案:

答案 0 :(得分:0)

您可以使用csv模块来读取文件:

import csv

t = []
v = []
with open(Pname, "r") as patient_f:
    csv_f = csv.reader(patient_f, delimieter='delimiter_between_columns')
    for row in csv_f:
        t.append(row[0])
        v.append(row[1])

答案 1 :(得分:0)

你可以做的是使用numpy为你订购列:

import numpy as np
file = np.loadtxt("filename.txt", delimiter=',') #do not need delimiter if your file is not csv. 
t = file[:,0]
v = [:,1]

plt.plot(t, v)
plt.show()
plt.xlabel('time (v)')
plt.ylabel('Velocity (m/s)')
plt.title(pacient+"plot")
plt.savefig("test.png")
plt.show()

没有numpy的另一种方式:

file = open('filename.txt').readlines()
file = [map(int, i.strip('\n').split()) for i in file]
new_data = [list(i) for i in zip(*file)]

plt.plot(new_data[0], new_data[1])
plt.show()