Python读取CSV表格打印指定列报错TypeError的解决方法
问题根因说明
input()是用于接收用户键盘输入的函数,input('table.csv')只会把table.csv作为提示文本输出到终端,等待用户输入后返回字符串类型的输入内容。你代码里的pd变量实际存储的是字符串,并非CSV表格对象,因此用pd['a']对字符串做非整数索引才会触发TypeError: string indices must be integers报错。col = input('a') or col = pd['a']属于语法错误,Python不支持该类连续赋值逻辑。
正确实现方案
方案1:使用Python内置csv库(无需额外安装依赖)
仅打印a列内容
import csv with open('table.csv', 'r', encoding='utf-8') as csv_file: # 以字典格式读取CSV,自动将第一行作为键名,skipinitialspace自动去除字段前后多余空格 csv_reader = csv.DictReader(csv_file, skipinitialspace=True) for row in csv_reader: print(row['a'])
打印整个CSV表格内容
import csv with open('table.csv', 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file, skipinitialspace=True) for row in csv_reader: print(row)
方案2:使用pandas库(更适合表格数据处理)
首先执行命令安装pandas:pip install pandas
仅打印a列内容
import pandas as pd df = pd.read_csv('table.csv', skipinitialspace=True) print(df['a'])
打印整个CSV表格内容
import pandas as pd df = pd.read_csv('table.csv', skipinitialspace=True) print(df)
内容的提问来源于stack exchange,提问作者Ling
相关产品推荐
相关产品推荐

