gpt4 book ai didi

python - 使用 csv 模块在 Python 中读取 csv 文件

转载 作者:行者123 更新时间:2023-11-30 22:34:14 25 4
gpt4 key购买 nike

我正在尝试使用 csv 模块在 Python 中读取 csv 文件。为此,我使用读取器变量:

 with open('oneOrganization.csv', 'r', newline='') as csvfile2:
reader2 = csv.DictReader(csvfile2, delimiter=',')

for row in reader2:
if row["role"] == []:
row_dict['Role'] = "User"
else:
row_dict['Role'] = row["role"]

但是,运行该程序时,我意识到它确实进入了循环,尽管 cvs 文件存在并且确实名为 oneOrganization.csv。这可能是什么原因?

我是从Python开始的,通常这种方法是有效的。

最佳答案

阻止代码访问 if 循环 if row['Role']==[] 的问题是因为您试图以错误的方式查找空元素。
试试这个:

方法一:

with open('oneOrganization.csv','r') as file:
reader = csv.DictReader(file,delimiter=',')
my_list = list(reader)
for row in reader:
if row['test1'] in (None,''): # to check if cell is empty
row_dict['Role'] = "User"
else:
row_dict['Role'] = row["role"]

方法2:由@Jean-François Fabre提供

with open('oneOrganization.csv','r') as file:
reader = csv.DictReader(file,delimiter=',')
for row in reader:
if not row['test1']:
row_dict['Role'] = "User"
else:
row_dict['Role'] = row["role"]

方法 3:“优雅的单衬” - 作者:@Jean-François Fabre

with open('oneOrganization.csv','r') as file:
reader = csv.DictReader(file,delimiter=',')
for row in reader:
row_dict['Role'] = row["role"] or "User"

我在一个 csv 示例上尝试了它,可以如下表示:(np.array 形式)

[['test1' 'test2' 'test3']
[ 1 2 3 ]
[ 11 22 33 ]
[ 222 333]]

并使用此代码:

import csv

with open('test_csv.csv','r') as file:
reader = csv.DictReader(file,delimiter=',')
for row in reader:
if row['test1'] in (None,''):
print('no')
else:
print(row['test1'])

或者使用方法2:

import csv

with open('test_csv.csv','r') as file:
reader = csv.DictReader(file,delimiter=',')
for row in reader:
if not row['test1']:
print('no')
else:
print(row['test1'])

或者方法3

import csv

with open('test_csv.csv','r') as file:
reader = csv.DictReader(file,delimiter=',')
for row in reader:
print(row['test1'] or 'no')

输出:

1
11
no

可以引用这个topic有关如何检查 csv 文件中的“单元格”是否为空的更多信息。

关于python - 使用 csv 模块在 Python 中读取 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44901370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com