簡體   English   中英

在python中寫入一個csv文件並使用列名讀取它

[英]write in a csv file in python and read it using the column name

雖然我已經寫了這段代碼

import csv
    with open('persons.csv', 'w') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',',quotechar='|')
        filewriter.writerow(['Name', 'Profession'])
        filewriter.writerow(['Derek', 'Software Developer'])
        filewriter.writerow(['Steve', 'Software Developer'])
        filewriter.writerow(['Paul', 'Manager'])

我得到的結果是

['Name', 'Profession']
[]
['Derek', 'Software Developer']
[]
['Steve', 'Software Developer']
[]
['Paul', 'Manager']
[]

它在兩者之間留了一條線。 怎么解決???

還有一件事我想使用他們的列名從 csv 讀取數據,即

import csv
with open('persons.csv') as f:
    reader = csv.reader(f)
 
  
    for Name, Profession in reader:
        print(Name, Profession)

--當我運行此代碼時,它顯示錯誤..

 for Name, Profession in reader:
ValueError: not enough values to unpack (expected 2, got 0)

請建議它如何工作

csv.writer將 \\r\\n 寫入文件。 如果您運行的是 Windows,請使用以下命令打開文件

with open('persons.csv', 'w', newline='') as csvfile:

一旦你有了這個,空行就會消失

第二個問題是由於第一個問題。 由於您有空行,因此 reader 有這些行的 0 個項目,因此是例外。

暫無
暫無

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

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