簡體   English   中英

Python錯誤地引用了csv中的列

[英]Python incorrectly referencing column in csv

Python:3.6版

編輯器:Notepad ++

鏈接到文件: GitHub存儲庫


嘗試引用list.csv中的各個列

我可以引用整列,但是當我使用下標時,它僅引用一個字符。

下面是代碼( GitHub上的鏈接

import csv
import re

with open("search_file.csv") as source, open("list.csv") as module_names, open("Final_File.csv","w",newline="") as result:
    reader=csv.reader(source)
    module=csv.reader(module_names)
    writer=csv.writer(result)
    for s in module_names:
        print(s)
        k=s[1]
        l=s[2]
        print(k)
        print(l)

這是輸出

choco,Chocolate

h
o
shake,Milkshake

h
a
lime,Lemon Meringue

i
m

但是,這是我正在尋找的輸出。 我要去哪里錯了?

choco,Chocolate

choco
Chocolate

shake,Milkshake

shake
Milkshake

lime,Lemon Meringue

lime
Lemon Meringue

為了遍歷CSV的行,可以遍歷reader對象(即module )。

然后,您可以打印以逗號分隔的行以及第一和第二列(其中列索引從0開始)。

import csv
import re

with open("search_file.csv") as source, open("list.csv") as module_names, open("Final_File.csv","w") as result:
    reader=csv.reader(source)
    module=csv.reader(module_names)
    writer=csv.writer(result)
    for s in module:
        print(','.join(s))
        print ''
        k=s[0]
        l=s[1]
        print(k)
        print(l)
        print ''

暫無
暫無

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

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