简体   繁体   中英

Convert Text file into Array

So I've done a bit of researching and use a variety of different methods, but nothing seems to work. I'm trying to have a program read a txt file in my folder, then convert into an array so that a different program can call that program and initiate the program of the other.

Below is the current code I have.

The print is to test and see if the output is true. In return, however, I get []. It supposed to fill in things like Zero, Guskgu, Tyran, etc.

Note that I'm new to Python and currently using the most recent version 3.

profiles = []
def readFile(Users):
        fileObj = open("Usernames.txt", "r") #opens the file in read mode
        profiles = fileObj.read().splitlines() #puts the file into an array
        fileObj.close()
        return profiles
print(profiles)

You constructed readFile(Users) but if you want to change profiles you need to call the method and pass in its parameters.

Im not sure what Users is but something like,

arr = readFiles(Users)
print(arr)

I removed Users and ran it with no parameters and it worked fine, also make sure the.txt file is in the same directory as your.py file.

def read_file(filename):
    lines = []
    with open(filename, 'r') as f:
        for line in f:
            lines.append(line.strip())
    return lines

print(read_file('filename.txt'))

The txt file:

lorem
ipsum
dolor
sit
amet

Output ['lorem', 'ipsum', 'dolor', 'sit', 'amet']

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