简体   繁体   中英

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. 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:

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. Be sure to use something like:

fileContentsList = loadFile(...)

outside of the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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