简体   繁体   English

在Python 3.x中将文本文件转换为列表

[英]Converting a text file to a list in Python 3.x

I'm trying to build a function that reads lines of text and then saves each line as part of a list. 我正在尝试构建一个函数,该函数读取文本行,然后将每一行保存为列表的一部分。 However, when I try to call the variable for the list in Python after running the function, the interpreter tells me that the variable has not been assigned. 但是,当我尝试在运行函数后在Python中为列表调用变量时,解释器告诉我尚未分配变量。 Here is a segment of my code: 这是我的代码的一部分:

   def loadFile(filename1='word1.txt', filename2='word2.txt', filename3='word3.txt') :

        dataFile = open(filename1, "r")
        fileContentsList = []

        for eachLine in dataFile:
            fileContentsList.append(eachLine.rstrip())

        dataFile.close()
        return fileContentsList

When I run the code it prints the list but returns this error when I call fileContentsList: 当我运行代码时,它将打印列表,但是在我调用fileContentsList时返回此错误:

Traceback (most recent call last):
    File "<pyshell#1>", line 1, in <module>
        fileContentsList
    NameError: name 'fileContentsList' is not defined

Any assistance would be greatly appreciated! 任何帮助将不胜感激!

If you're trying to access fileContentsList from outside the method, it won't be in scope. 如果您尝试从方法外部访问fileContentsList,则它将不在范围内。 Be sure to use something like: 确保使用类似:

fileContentsList = loadFile(...)

outside of the method. 方法之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM