在处理 CSV 文件时,经常会遇到某些文件不存在某些列的情况。例如,有一个文件夹里有多个 CSV 文件,其中一些文件具有 “Country” 列,而另一些文件没有。如果使用以下代码来读取这些文件,就会出现错误:
import csv
import glob
files = glob.glob('..\\*.csv')
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
for file in files:
countries = []
with open('data.csv', newline='') as infile:
reader = csv.DictReader(infile)
for row in reader:
countries.append(row['Country'])
print(countries)
当代码尝试读取不存在的 “Country” 列时,就会引发以下错误:
KeyError: 'Country'
2、解决方案
要解决这个问题,可以采用以下几种方法:
1. 检查字段是否存在
在读取文件之前,可以先检查 “Country” 列是否存在。如果存在,再继续读取该列。例如:
import csv
import glob
files = glob.glob('..\\*.csv')
for file in files:
countries = []
with open('data.csv', newline='') as infile:
reader = csv.DictReader(infile)
if 'Country' in reader.fieldnames:
for row in reader:
countries.append(row['Country'])
print(countries)
2. 使用 .get() 方法
可以使用 .get() 方法来读取不存在的列。如果列不存在,.get() 方法会返回 None。例如:
import csv
import glob
files = glob.glob('..\\*.csv')
for file in files:
countries = []
with open('data.csv', newline='') as infile:
reader = csv.DictReader(infile)
for row in reader:
countries.append(row.get('Country'))
print(countries)
3. 使用 .setdefault() 方法
可以使用 .setdefault() 方法来读取不存在的列。如果列不存在,.setdefault() 方法会创建一个新的列,并将其值设置为指定的默认值。例如:
import csv
import glob
files = glob.glob('..\\*.csv')
for file in files:
countries = []
with open('data.csv', newline='') as infile:
reader = csv.DictReader(infile)
for row in reader:
countries.append(row.setdefault('Country', 'Unknown'))
print(countries)
4. 使用 try-catch 块
可以使用 try-catch 块来捕获 KeyError。如果出现 KeyError,则可以忽略该错误。例如:
import csv
import glob
files = glob.glob('..\\*.csv')
for file in files:
countries = []
with open('data.csv', newline='') as infile:
reader = csv.DictReader(infile)
for row in reader:
try:
countries.append(row['Country'])
except KeyError:
pass
print(countries)
5. 使用列表解析
可以使用列表解析来简化代码。例如:
import csv
import glob
files = glob.glob('..\\*.csv')
for file in files:
with open('data.csv', newline='') as infile:
reader = csv.DictReader(infile)
if 'Country' in reader.fieldnames:
countries = [row['Country'] for row in reader]
else:
countries = []
print(countries)
这几种方法都可以解决 CSV 文件中不存在某些列的错误。具体使用哪种方法,取决于具体情况。