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)
CodePudding user response:
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.
CodePudding user response:
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']