首先,我将发布我的代码。我觉得有一个简单的答案,我不知何故忽略了。
questionsList=[]
answersList=[]
def retrieveQuestions():
f=open('Questions.txt')
questionsList=f.read().splitlines()
for row in f:
questionsList.append(row)
def retrieveAnswers():
with open('Answers.txt') as j:
answersList=list(j.read().splitlines())
retrieveQuestions()
retrieveAnswers()
print(questionsList)
print(answersList)
当我运行程序时,我得到的输出 [] [] 我查找了多种文件路径方法,多种读取方式和.splitlines((,但我仍然不知道出了什么问题。
目前,您的方法仅创建和填充列表,而没有其他内容 - 没有屏幕输出或返回。只需向函数添加一个return
,并为变量赋值,然后在每个调用的函数中打印或print
。而且,当您在方法中定义变量时,您不需要在顶部进行全局变量赋值。
返回和分配
def retrieveQuestions():
f=open('1222_2016_2016-2017.csv')
questionsList=f.read().splitlines()
for row in f:
questionsList.append(row)
f.close()
return questionsList
def retrieveAnswers():
with open('ODDFiles.csv') as j:
answersList=list(j.read().splitlines())
return answersList
questionsList = retrieveQuestions()
answersList = retrieveAnswers()
print(questionsList)
print(answersList)
内部打印
def retrieveQuestions():
f=open('1222_2016_2016-2017.csv')
questionsList=f.read().splitlines()
for row in f:
questionsList.append(row)
print(questionsList)
def retrieveAnswers():
with open('ODDFiles.csv') as j:
answersList=list(j.read().splitlines())
print(answersList)
retrieveQuestions()
retrieveAnswers()
试试看:
questionsList=[]
answersList=[]
def retrieveQuestions():
f=open('Questions.txt', 'r')
questionsList = f.readlines().splitlines()
def retrieveAnswers():
with open('Answers.txt', 'r') as j:
answersList = j.readlines().splitlines()
retrieveQuestions()
retrieveAnswers()
print(questionsList)
print(answersList)
苏格斯:
def read_file(filename):
return open(filename, 'r').readlines().splitlines()
questionsList = read_file('Questions.txt')
answersList = read_file('Answers.txt')
print(questionsList)
print(answersList)