使用Python特殊格式从文件中读取数据

时间:2014-01-15 11:25:05

标签: python

我有一个问题。我有一些数据文件,其结构是:

第一行

219,241,280,369,402.7,472.7,520,553.3,588.7,635.3,678.7,734.7,795.3,880,914,968.7,1030.7,1085.3,1185.3

第二行

436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7

在第一行中是x的值,在第二行中是y的值。 现在我希望这些值进入这种形状:

x=r_[219,241,280,369,402.7,472.7,520,553.3,588.7,635.3,678.7,734.7,795.3,880,914,968.7,1030.7,1085.3,1185.3]

y=r_[436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7]

我在添加r_时遇到问题。 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

快速回答:

firstline = '436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7'
secondline = '436.5,430.5,426,418,420,413.3,410,406.7,404,402,407.3,410,413.3,418.7,420,428,433.3,440.7,458.7'

x = 'r_[' + firstline + ']'
y = 'r_[' + secondline + ']'

我真的不知道你真正想要的是什么......

答案 1 :(得分:0)

好吧,如果我理解正确的话,这就是你应该做的(假设文件名是test.txt):

with open("test.txt", "r") as f:
    firstline = f.readline().rstrip("\n")
    secondline = f.readline().rstrip("\n")

firstline = "x=r_[" + firstline + "]\n"
secondline = "y=r_[" + secondline + "]\n"
data = firstline+secondline

with open("test2.txt", "w") as f:  # <-- changed name here, just in case
    f.write(data)