簡體   English   中英

在 Python 中從 CSV 文件中讀取數據

[英]Reading data from a CSV file in Python

我正在從包含以下數據的 CSV 文件 (xyz.CSV) 中讀取數據:

col1,col2,col3,col4
name1,empId1,241682-27638-USD-CIGGNT ,1
name2,empId2,241682-27638-USD-OCGGINT ,1
name3,empId3,241942-37190-USD-GGDIV ,2
name4,empId4,241942-37190-USD-CHYOF ,1
name5,empId5,241942-37190-USD-EQPL ,1
name6,empId6,241942-37190-USD-INT ,1
name7,empId7,242066-15343-USD-CYJOF ,3
name8,empId8,242066-15343-USD-CYJOF ,3
name9,empId9,242066-15343-USD-CYJOF ,3
name10,empId10,241942-37190-USD-GGDIV ,2

當我使用循環對其進行迭代時,我可以通過以下代碼逐行打印數據,並且僅打印 column1 數據。

file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[0]
    print t

通過上面的代碼,我只能得到第一列。

如果我嘗試打印 line[1] 或 line[2] 它會給我以下錯誤。

    file=open( path +"xyz.CSV", "r")
    reader = csv.reader(file)
    for line in reader:
        t=line[1],[2]
        print t

t=line[1],line[2]
IndexError: list index out of range

請建議打印 column2 或 column3 的數據。

這是我如何獲得第 2 列和第 3 列:

import csv

path = 'c:\\temp\\'

file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[1],line[2]
    print(t)

結果如下:

('col2', 'col3')
('empId1', '241682-27638-USD-CIGGNT ')
('empId2', '241682-27638-USD-OCGGINT ')
('empId3', '241942-37190-USD-GGDIV ')
('empId4', '241942-37190-USD-CHYOF ')
('empId5', '241942-37190-USD-EQPL ')
('empId6', '241942-37190-USD-INT ')
('empId7', '242066-15343-USD-CYJOF ')
('empId8', '242066-15343-USD-CYJOF ')
('empId9', '242066-15343-USD-CYJOF ')
('empId10', '241942-37190-USD-GGDIV ')

雖然這是一個很老的問題,但只想分享我的建議。 發現在數據框中使用 pandas 讀取 csv 並訪問數據更容易。

import pandas

df = pandas.read_csv('<path/to/your/csv/file>')

print(df)
#OUTPUT
#     col1     col2                       col3  col4
#0   name1   empId1   241682-27638-USD-CIGGNT      1
#1   name2   empId2  241682-27638-USD-OCGGINT      1
#2   name3   empId3    241942-37190-USD-GGDIV      2
#3   name4   empId4    241942-37190-USD-CHYOF      1
#4   name5   empId5     241942-37190-USD-EQPL      1
#5   name6   empId6      241942-37190-USD-INT      1
#6   name7   empId7    242066-15343-USD-CYJOF      3
#7   name8   empId8    242066-15343-USD-CYJOF      3
#8   name9   empId9    242066-15343-USD-CYJOF      3
#9  name10  empId10    241942-37190-USD-GGDIV      2

#you can access any column using

df['col2']
#OUTPUT
#0     empId1
#1     empId2
#2     empId3
#3     empId4
#4     empId5
#5     empId6
#6     empId7
#7     empId8
#8     empId9
#9    empId10
#Name: col2, dtype: object


#Or print a specific value using
df['col2'][0]

更新:我主要在我的項目中使用 Pandas,所以發現使用它來讀取 csv 也更容易。 還有其他專用庫可用於讀取 CSV(創建您自己的 CSV 閱讀器也應該是幾行代碼)。

您的第一行只有一列,因此該過程失敗並且不會繼續。 要解決,只需跳過第一行

>>> with open( path, "r") as file:
...     reader = csv.reader(file)
...     for idx,line in enumerate(reader):
...         if idx>0:
...             t=line[1],line[2]
...             print t
... 
('empId1', '241682-27638-USD-CIGGNT ')
('empId2', '241682-27638-USD-OCGGINT ')
('empId3', '241942-37190-USD-GGDIV ')
('empId4', '241942-37190-USD-CHYOF ')
('empId5', '241942-37190-USD-EQPL ')
('empId6', '241942-37190-USD-INT ')
('empId7', '242066-15343-USD-CYJOF ')
('empId8', '242066-15343-USD-CYJOF ')
('empId9', '242066-15343-USD-CYJOF ')
('empId10', '241942-37190-USD-GGDIV ')

希望它能解決問題

import csv
file=open( "xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[0]+","+line[1]
    print (t)
import csv
csv_file=open("xyz.csv", "r")
reader = csv.reader(csv_file)

for row in reader:
    print(" ".join(row[:2]))

Output :- 
col1 col2
name1 empId1
name2 empId2
name3 empId3
name4 empId4
name5 empId5
name6 empId6
name7 empId7
name8 empId8
name9 empId9
name10 empId10

只需將值作為切片放入行中。 下面是打印第 2 列和第 3 列的代碼。

import csv
csv_file=open("xyz.csv", "r")
reader = csv.reader(csv_file)

for row in reader:
    print(" ".join(row[1:3]))

output:
col2 col3
empId1 241682-27638-USD-CIGGNT 
empId2 241682-27638-USD-OCGGINT 
empId3 241942-37190-USD-GGDIV 
empId4 241942-37190-USD-CHYOF 
empId5 241942-37190-USD-EQPL 
empId6 241942-37190-USD-INT 
empId7 242066-15343-USD-CYJOF 
empId8 242066-15343-USD-CYJOF 
empId9 242066-15343-USD-CYJOF 
empId10 241942-37190-USD-GGDIV 

要在 Python 中讀取和寫入文本文件,可以使用以下語法:

f = open('helloworld.txt','r')
message = f.read()
print(message)
f.close()


f = open('helloworld.txt','w')
f.write('hello world')
f.close()

要讀取 CSV 文件,請遵循以下代碼: results = [] enter code here其中 open("C:/Users/Prateek/Desktop/TA Project/data1.csv") 作為 inputfile: for line in inputfile: results.append (line.strip().split(','))

有一個簡單的方法可以查看更多信息: Python CSV Docs

with open(filename, 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in spamreader:
            data.append(row)

您也可以在不導入 pandas 和 csv 的情況下讀取 csv 數據

with open('testdata.csv', 'r') as f:
    results = []
    for line in f:
            words = line.split(',')
            results.append((words[0], words[1:]))
    print (results)

您可以使用表庫。

第 1 步:打開並存儲您的 CSV 文件。

import tablebase
MyTable = tablebase.CsvTable("<path/to/your/csv/file>")

第 2 步:獲取您的專欄。

print(MyTable.get_col("ColumnName"))

這將返回您的列內容列表。

加載預處理的 CSV 數據

data_preprocessed = pd.read_csv('file_name.csv')

暫無
暫無

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

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