因此,我的目录中有一个CSV文件(league.csv'),我想通过Python访问该文件。
当我这样做时:
with open('league.csv', 'r') as csvFile:
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
效果很好。但是,当我尝试将其转换为函数时,它将无法正常工作:
def createLeague(csv):
with open(csv, 'r') as csvFile:
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
return
如果我使用以下方式致电
: createLeague('league.csv')
我收到错误
csvReader = csv.reader(csvFile)
AttributeError: 'str' object has no attribute 'reader'
这没有意义,因为type(csvFile)不是str,我做的和上面完全一样吗?
有人可以帮我吗,我真的很沮丧!
谢谢!
答案 0 :(得分:0)
请勿在函数定义中使用库的名称作为变量的名称。
答案 1 :(得分:0)
查看内联注释出了什么问题。
import csv # "csv" variable at "with open..." overwrites
# cvs module.
from csv import reader # required to use the function "reader" from csv.
def createLeague(csv): # "csv" variable overwrites cvs module.
with open(csv, 'r') as csvFile:
csvReader = reader(csvFile) # skip the csv. here and it works for you.
next(csvReader)
for line in csvReader:
print(line[0])
return
或者:
下面的示例更改了 csv文件名 ,但不会覆盖您刚刚加载的 csv模块 。混淆会触发错误发生。
import csv
#from csv import reader
def createLeague(csv_file):
with open(csv_file, 'r') as csvFile: # changed variable "csv" filename.
csvReader = csv.reader(csvFile)
next(csvReader)
for line in csvReader:
print(line[0])
return