Files

187 lines
6.3 KiB
Python

#collection of functions used for creating and implementing output
from createOutput.jsonConvert import JsonConvert
from createOutput.textConvert import TextConvert
from createOutput.plainTextConvert import PlainTextConvert
from postData import PostData
import os
def yesno_():
#collects and verifies yes/no input; returns true if yes, false if no
choice = input("(y/n): ")
while not(choice.lower() == "y" or choice.lower() == "n"):
print("Invalid input. Try again.")
choice = input("(y/n): ")
if choice.lower() == "y":
return True
else:
return False
def getDirectory(extension):
#asks for a file directory and name to save with and returns that data
#
#extension = string containing file extension to save file as
path = "" #path to output file
fileName = "" #name of file
print("Please enter directory to save output to.") #collect user's desired save directory
path = input(": ")
while not os.path.isdir(path):#validate path
print("Invalid pathname. Try again.")
path = input(": ")
if len(path.split("/")) > 1: path = "\\".join(path.split("/")) #replace all '/' with '\' if '/' is used
if path[-1] == "\\": path = path[:-1] #remove any trailing '\'
print("What would you like to name your file?")
fileName = input(": ")
fileName = fileName.split(extension)[0] #remove file extension if user included it
while os.path.exists(path + "\\" + fileName + extension):#if file at path already exists, have user confirm decision
print("A file with the same name already exists in the path that you specified. Would you like to replace it?")
ui = yesno_()
if ui:
break
else:
print("Would you like to select a new directory?")
ui = yesno_()
if not ui:
fileName = input(": ").split(extension)[0]
else:
return getDirectory(extension) #restart function if user wants to change directory
return path, fileName
def createText(posts, toFile):
#creates text file or prints out data
#returns true if file successfully created or data successfully printed
#returns false if file could not be created or user decides agains plain-text output
#
#posts = list of PostData objects
#toFile = True if output being saved to file, False if being printed for copy/paste output
if toFile:#save to text file
path, fileName = getDirectory(".txt")#path to file and name of text file to save
textFileCreate = TextConvert()
#add posts to textFileCreate
for post in posts:
textFileCreate.unpackPostData(post)
#create text file
print("\nCreating file...")
if not textFileCreate.exportText(path, fileName):
#if program failed to create file, ask if uer wants to try
# different dierectory, or give up
print("""
Error: Failed to create file.
What would you like to do?
(1) try different drectory
(2) try something else
""")
ui = input(": ")
while not ui.isdigit() or not (0 < int(ui) < 3):
print("Error: Input must be a number between 1 and 2. Try again.")
ui = input(": ")
if int(ui) == 1:#try again with different path
textFileCreate = 0 #clear data to save memory
return createText(posts, toFile)
if int(ui) == 2:#give up and return false
return False
else:#text file successfully created
print("Successful")
print(f"File saved to {path}\\{fileName}.txt")
return True
else:#create plain text output
print("Are you sure you want to do this? This is not recommended if you have a lot of posts. (y/n)")
answer = input(": ")
while not (answer.lower() == 'y' or answer.lower() == 'n'):
print("Answer should be 'y' or 'n'. Try again.")
answer = input(": ")
if answer == 'n':
return False
textOut = PlainTextConvert()
for post in posts:
textOut.unpackPostData(post)
textOut.printOutput()
return True
def createJson(posts):
#creates json file using JsonConvert class
#returns true if file successfully created, false if not
#
#posts = list of PostData objects
path, fileName = getDirectory(".json") #path to file and name of JSON file to save
jsonCreate = JsonConvert() #jsonConvert object
#add posts to jsonCreate
for post in posts:
jsonCreate.unpackPostData(post)
#create json file
print("\nCreating file...")
if not jsonCreate.exportJson(path, fileName):
#if program failed to create file, ask if uer wants to try
# different dierectory, or give up
print("""
Error: Failed to create file.
What would you like to do?
(1) try different drectory
(2) try something else
""")
ui = input(": ")
while not ui.isdigit() or not (0 < int(ui) < 3):
print("Error: Input must be a number between 1 and 2. Try again.")
ui = input(": ")
if int(ui) == 1:#try again with different path
jsonCreate = 0#clear data to save memory
return createJson(posts)
if int(ui) == 2:#give up and return false
return False
else:#json file successfully created
print("Successful.")
print(f"File saved to {path}\\{fileName}.json")
return True
def outputSelect(posts):
#allows user to select an output method and runs the appropriate function
#
#posts = posts to be output
writeSuccess = True #true when output was successfully written to file
print("""
How would you like your data outputed?
(1) JSON
(2) Text File
(3) Plain Text
""")
ui = input(": ")
while not ui.isdigit() or not (0 < int(ui) < 4):
print("Error: Input must be a digit between 1 and 3. Try again.")
ui = input(": ")
if ui == "1":#json output
writeSuccess = createJson(posts)
elif ui == "2":#text output
writeSuccess = createText(posts, True)
else: #copy/paste
writeSuccess = createText(posts, False)
if not writeSuccess:
outputSelect(posts) #if failed to write to file, restart process