Re: [問題] 請問讀取CSV檔,如何讓他LIST方式呈現

看板Python作者 (阿真)時間14年前 (2011/08/26 22:26), 編輯推噓2(205)
留言7則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《lthstar (Never Say Never)》之銘言: : 正在學習python中,目前正在寫讀取csv檔, : 裡面內容如下: : John Cleese, Ministry of Silly Walks, 5555421, 2011/10/27 : Eric Idle, Spamalot, 55553311, 2011/3/29 你的csv檔很奇怪 逗號後有空格 不像一般的csv檔 不過很整齊 有解 : 圖片: : http://img696.imageshack.us/img696/1309/2011826053846.jpg
我看起來圖片像支青蛙?? : 我的程式: : def load_friends(filename): : """takes the name of a file containing friends information : as described in the introduction and returns a dictionary containing : information about the friends in the file : load_friends(str) -> dict(str:str) : """ : f = open(filename, 'U') 小的受教的<(_ _)> U是可以解決換行符號的吧?(上網查的) : info = {} : for i in f: : i_info =i.split(',') : info[i_info[0]]=i_info[1:] : f.close() : print"your current friend list:" : return info : 但最後return 回來都會出現多出\n : 如下: : your current friend list: : {'John Cleese': ['Ministry of Silly Walks', '5555421', '27-Oct\n'], 'Eric : Idle': ['Spamalot', '55553311', '29-Mar\n']} 很好奇為什麼值前面的空格都不見了?? 一般我是用 friend_info={} for line in file_: linelist = line.split(", ") #用逗號+空格 linelist[-1] = linelist[-1].rstrip("\n") #去掉換行 name = linelist[0] info = linelist[1:] friend_info[name] = info 這樣應該就行了 (上面程式我沒跑過…) : 想請問要怎麼把\n拿掉呢? 我通常是用 linelist[-1] = linelist[-1].rstrip("\n") : 假如我想要一段資料分行列的話, : 要怎麼寫呢? 這是什麼意思? 是說值要換行嗎? : 問題可能很簡單,但我一直試,就拿不掉\n, : 用with 寫的話,是不會有\n出來,不過會多一個[ ]出來 : 我for迴圈底下是這樣設的 : for i in loader: : info.setdefault(i[0],[]).append(i[1:]) 這裡我看不懂... : 可以幫我看一下嗎? : 謝謝! 參考上方 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.63.249 ※ 編輯: KSJ 來自: 140.112.63.249 (08/26 22:27) ※ 編輯: KSJ 來自: 140.112.63.249 (08/26 22:41)

08/27 10:41, , 1F
謝謝! 我來試試^^
08/27 10:41, 1F

08/27 11:15, , 2F
用 ', ' 如果碰到標準的 csv 就出國了, 我會用 strip()
08/27 11:15, 2F

08/27 11:31, , 3F
我試了!不能用', ',要',' 這樣才可以執行成功!THX
08/27 11:31, 3F

08/27 11:32, , 4F
ur大的也成功了!謝謝^^
08/27 11:32, 4F

08/27 12:22, , 5F
看起來 檔是一般的csv檔 與文章中的內容似乎不同??
08/27 12:22, 5F

08/27 12:53, , 6F
當初文字是複製IDLE上的,但CSV裡的文字間沒有空格!抱歉~
08/27 12:53, 6F

08/29 22:06, , 7F
其實也可以用re.sub,裡面塞regular expression
08/29 22:06, 7F
文章代碼(AID): #1ELwp-Tu (Python)
文章代碼(AID): #1ELwp-Tu (Python)