2017-10-15 112 views
-1
def reademail(): 
f = open("Y11email.csv", "r") 
line= "email"+ ","+"fname"+","+"sname"+"password"+"\n" 
for line in f: 
    email,fname,sname,password=line.split(", ")#splits each line however creates an extra space between the lines because of enter 
    password=password.strip()#strip removes the extra space between the lines 
    print(email,fname,sname,password) 
f.close() 

我是新來的python,所以我不明白我不斷收到的錯誤。我希望有人能解釋。如果您需要任何詳細信息,我會在編輯沒有足夠的值來解壓(預計4,得到1)的功能,python

email,fname,sname,password=line.split(", ")#splits each line however creates an extra space between the lines because of enter

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

我希望它打印這樣的:

[email protected] Name Surname fakepassword

[email protected] Z Y fakepassword

[email protected] Ray Check hello

編輯:我試圖在逗號後移除之間的空間,並試圖到.split( 「\ n」),但有

email,fname,sname,password=line.split("\n")#splits each line however creates an extra space between the lines because of enter

ValueError: not enough values to unpack (expected 4, got 2)

至少我得到了一個更大的價值XD

+1

這是因爲您的文件行沒有任何逗號btw您應該使用'csv'模塊讀取csv文件 –

+0

或者有逗號...只是沒有逗號後跟空格... :) –

+0

是的。 csv模塊_forever_ –

回答

0

而不是重新實現交流sv閱讀器,請使用Python標準庫中的csv module

實施例從文檔複製:

>>> import csv 
>>> with open('eggs.csv', newline='') as csvfile: 
...  spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') 
...  for row in spamreader: 
...   print(', '.join(row)) 
Spam, Spam, Spam, Spam, Spam, Baked Beans 
Spam, Lovely Spam, Wonderful Spam 

這顯示了規範的方法來讀取CSV文件。請注意,csv.reader會爲每次迭代生成一個字符串列表,因此您不必分割它。

您可以拆分之前,測試線的長度:

for row in Y11reader: 
    ll = len(row) 
    if ll != 4: 
     logging.warning('invalid row of {} items'.format(ll)) 
     continue # skip to next iteration. 
    email, fname, sname, password = row 
+0

logging.warning()變量出現錯誤,我想知道你是否知道爲什麼? – Ray

+0

@ray您必須導入['logging'](https://docs.python.org/3.6/howto/logging.html)模塊才能使用它。 –

0

的問題是你的輸入。您需要確保輸入中的每一行都具有這4個特徵,並且它們總是用逗號分隔。

當等式右邊的數值與右側變量數不匹配時,會發生此錯誤。一個例子是:

以下工作作爲線路被分成4個元素

line = "1,2,3,4" 
line_list = line.split(',') #Looks like [1,2,3,4] 
first, second, third, fourth = line.split(',') #Each element is assigned to each variable 

的列表,但下面不工作

line = "1,2,3" 
line_list = line.split(',') #Looks like [1,2,3] 
first, second, third, fourth = line.split(',') 

沒有一對一的映射元素的變量。因此,解釋器會發出一個錯誤,說not enough values to unpack (expected 4, got 3)。由於列表中有4個值(因爲等式左邊有4個變量,但只提供了3個變量)

+0

我試圖糾正輸入,但現在我的程序說有更多的項目要解壓比預期,你能幫助解釋爲什麼嗎? – Ray

+0

你能分享一些樣本輸入嗎? –

相關問題