从文件中读取,拆分并将其存储在变量中

时间:2017-03-04 07:42:55

标签: string python-3.x

我有一个包含以下数据的文件:

2905 5.0 10

1420 5.0 2

3011 5.0 2

659 5.0 2

121 5.0 1

1743 5.0 1

2056 5.0 1

2063 5.0 1

2185 5.0 1

2192 5.0 1

2198 5.0 1

2215 5.0 1

2562 5.0 1

2632 5.0 1

2675 5.0 1

2994 5.0 1

3038 5.0 1

3205 5.0 1

3245 5.0 1

3280 5.0 1

    f=open('/home/bhoots21304/Desktop/out12.txt','r')
    for line in f:
        a = line.strip().split('\t')
        (movieId, rating, views) = a

&安培;&安培;这段代码给我一个错误:

(movieId, rating, views) = a

ValueError: not enough values to unpack (expected 3, got 1)

有没有其他方法可以从文件中读取,拆分字符串并将其存储在某个变量中?

1 个答案:

答案 0 :(得分:0)

您将字符串拆分为\t,代表标签。在您的示例中,没有任何标签,您的值以空格分隔。这应该有效:

f=open('/home/bhoots21304/Desktop/out12.txt') #No need to use 'r', the default is 'r'
for line in f:
    if not line.strip(): continue #check to see if it's empty
    movieId, rating, views = line.strip().split(' ') #change it to a space
    #do stuff with them....

使用with语句首选打开文件,因为它会在程序退出时自动关闭文件:

with open('/home/bhoots21304/Desktop/out12.txt') as f:
    for line in f:
        if not line.strip(): continue #check to see if it's empty
        movieId, rating, views = line.strip().split(' ') #change it to a space
        #do stuff with them....