I have my own Python library that I made with help from @bigminiboss (or I helped bigminiboss to set it up is more accurate). Anyway, I can’t figure out how to include a text file as a resource for my Py files. I have one command in particular, rickRoll(), that I want to use a text file provided by the PyPi package when the user leaves it unspecified. How do I do this? So far, I have been unsuccessful.
Other
I copied the function verbatim. The user can specify the file path using “fileName”, but I want the default to be the file “text/rickRoll_short.txt” located in the PyPi package. I know how to do this for a local file, but I want the function to do it as part of the PyPi package. Note: I only need help accessing the file; I already have ways to improve and shorten this function but I need this done first.
############
# Rickroll #
############
# This can be used to do other things too.
def rickRoll(fileName, timePerLine=2, infinity="yes"):
from time import sleep
rick = open(fileName)
contents = rick.readlines()
def main():
clear()
x = 0
for fun in range(0, len(contents)):
print(contents[x].strip("\n"))
if contents[x] != "\n":
sleep(timePerLine)
x = x + 1
main()
while any(infinity == f for f in ["yes", "y"]):
main()
I don’t think pip transfers non-python files, if it does, you might need to get the package directory. I recommend copying the contents and putting it in a multiline string
Thanks for the advice. I think I’ll do that unless somebody else comes up with a way to actually use the text file. Multiline strings start and end with ''', right?
Except using multiline strings requires redoing the code. See a working demo of the problems it causes here. It prints them letter by letter. How do I reference a multiline string line by line instead of character by character?
from CoderElijah import clear
############
# Rickroll #
############
# This can be used to do other things too.
def rickRoll(fileName='', timePerLine=2, infinity="yes"):
from time import sleep
if fileName != '':
rick = open(fileName)
contents = rick.readlines()
else:
contents = '''Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
'''
contents=contents.split('\n')
def main():
clear()
x = 0
for fun in range(0, len(contents)):
print(contents[x].strip("\n"))
if contents[x] != "\n":
sleep(timePerLine)
x = x + 1
main()
while any(infinity == f for f in ["yes", "y"]):
main()
rickRoll()
Okay, so I marked a solution and now I got it working. I tried several times, but my own mistakes made it fail. Now, it works! Thank you both very much for the help.
Sample Py file to use this:
from os import system
system('pip install coderelijah') # I know you wouldn't normally do this
# in Python (and would use shell instead), but it puts all the commands
# and code into one part of this post.
from CoderElijah import *
rickRoll()