Re: [問題] 請問讀取CSV檔,如何讓他LIST方式呈現
※ 引述《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
08/27 11:15, 2F
→
08/27 11:31, , 3F
08/27 11:31, 3F
→
08/27 11:32, , 4F
08/27 11:32, 4F
→
08/27 12:22, , 5F
08/27 12:22, 5F
→
08/27 12:53, , 6F
08/27 12:53, 6F
推
08/29 22:06, , 7F
08/29 22:06, 7F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章