0
datafile = open("temp.txt", "r")
record = datafile.readline()

while record != '':
    d1 = datafile.strip("\n").split(",")
    print d1[0],float (d1[1])
    record = datafile.readline()

datafile.close()

临时文件包含

a,12.7
b,13.7
c,18.12

我无法获得输出。请帮忙。

4

4 回答 4

4

正确的代码应该是:

with open('temp.txt') as f:
    for line in f:
        after_split = line.strip("\n").split(",")
        print after_split[0], float(after_split[1])

您没有在代码中获得输出的主要原因是数据文件没有 strip() 方法,我很惊讶您没有收到异常。

我强烈建议您阅读 Python 教程 - 看起来您正在尝试用另一种语言编写 Python,这不是 一件好事

于 2012-06-20T20:06:40.133 回答
2

您想在线上调用 strip 和 split ,而不是文件。

代替

d1 = datafile.strip("\n").split(",")

d1 = record.strip("\n").split(",")

于 2012-06-20T20:05:37.570 回答
1

您使用文件处理程序进行操作,但应该在线工作

像这样d1 = record.strip("\n").split(",")

datafile = open("temp.txt", "r")
record = datafile.readline()

while record != '':
    d1 = record.strip("\n").split(",")
    print d1[0],float (d1[1])
    record = datafile.readline()

datafile.close()
于 2012-06-20T20:06:48.467 回答
0

也许以下内容对您更有效(评论作为解释):

# open file this way so that it automatically closes upon any errors
with open("temp.txt", "r") as f:
    data = f.readlines()

for line in data:
    # only process non-empty lines
    if line.strip():
        d1 = line.strip("\n").split(",")
        print d1[0], float(d1[1])
于 2012-06-20T20:12:48.560 回答