将数据导入代码的问题

时间:2013-06-27 01:30:26

标签: python python-3.x

所以我正在尝试制作一个代码,它将从文本文件中导入数据并使用matplotlib将其绘制到目前为止我所拥有的内容:

import matplotlib.pyplot as plt


x = []
y = []

readFile = open ('C:/Users/Owner/Documents/forcecurve.txt', 'r')

sepFile = readFile.read().split('\n')

readFile.close()

for plotPair in sepFile:
    xAndY = plotPair.split('\t')
    x.append(int (xAndY[0]))
    y.append(int (xAndY[1]))
print x
print y

plt.plot (x, y)



plt.xlabel('Distance (Nanometers)')
plt.ylabel('Force (Piconewtons)')

plt.show()

运行此操作后,我收到错误

ValueError: invalid literal for int() with base 10: '1,40.9'

1 个答案:

答案 0 :(得分:0)

您的文件似乎以逗号分隔(1,40.9),而非制表符分隔,因此您需要使用逗号分隔而不是制表符。变化

    xAndY = plotPair.split('\t')

    xAndY = plotPair.split(',')

或者,使用csv模块读取文件可能更容易。举个简单的例子:

import csv

readFile = open ('C:/Users/Owner/Documents/forcecurve.txt', 'r')

x = []
y = []

r = csv.reader(readFile)
for x1, y1 in r:
    x.append(int(x1))
    y.append(int(y1))

readFile.close()