簡體   English   中英

將CSV文件導入列表python

[英]Importing CSV file into list python

我這里有點問題。 我需要讀取一個txt文件並將其存儲到一個列表中,我已經這樣做了......但問題是我需要操作一些列,比如乘以30然后等等。 (我還在學習python)(它的python 3.4)

test.txt文件:

Abacate;Para;PA;-1.1166667;-49.65
Abacate;Amazonas;AM;-3.9463889;-62.9038889

代碼:

def readFile():
  with open('test.txt') as f:
    reader = csv.reader(f,delimiter=";")
    #reader.next()
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)

但是,當我嘗試使用時

    for i in range(0,len(columns[3])):
        listTest.append(columns[3][i]*3)

結果是:

['-1.1166667-1.1166667-1.1166667']
['-1.1166667-1.1166667-1.1166667', '-3.9463889-3.9463889-3.9463889']

預期:

['-3.3500001','-11.8391667']

有一個更好的方法嗎?

Python正在將數字作為字符串讀取,因此當你執行*3它會認為“啊!Matt要我連續三次放入字符串!”

如果你先把它轉換成浮點數,那就沒關系了:

for i in range(0,len(columns[3])):
    listTest.append(float(columns[3][i])*3)

你需要將columns[3][i]解析為浮點數

listTest.append(float(columns[3][i])*3)

因為

'any_string'*3
>>any_stringany_stringany_string
 100*3
>>300
import csv
def readFile(infilepath):
    answer = []
    with open(infilepath) as infile:
        for *_head, a, _b in csv.reader(infile, delimiter';'):
            answer.append(float(a) * 3)
    return answer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM