How can I make python save a file in a different location? -
my python project has 2 files. made folder called files
when user writes in text editor, saves folder, when user opens textviewer, type file name , looks in files
directory. how able this?
code text editor:
def edit(): os.system('cls' if os.name == 'nt' else 'clear') print ("edit") print ("-------------") print ("note: naming current document same different document replace other document one.") filename = input("plese enter file name.") file = open(filename, "w") print ("file: " +filename+".") lines = get_lines() file.write('\n'.join(lines)) def get_lines(): print("enter 'stop' end.") lines = [] line = input() while line != 'stop': lines.append(line) line = input() return lines
text viewer code:
def textviewer(): os.system('cls' if os.name == 'nt' else 'clear') print ("text viewer.") file_name = input("enter text file view: ") file = open(file_name, "r") print ("loading text...") time.sleep(0.5) os.system('cls' if os.name == 'nt' else 'clear') print(file.read()) edit_text = input("would edit it? (y yes, n no)") if edit_text == "y": file = open(file_name, "w") print ("you in edit mode.") lines = get_lines file.write('\n'.join(lines)) time.sleep(2) if edit_text == "n": print ("press enter exit") input()
if don't want filename
considered relative current working directory, should transform more specific absolute path before passing open
. use os.path.join
combine directory name , file name in platform independent way:
directory = "/media/general/projects/files" filename = input("plese enter file name.") file = open(os.path.join(directory, filename), "w")
unrelated issue, involving same parts of code, i'd suggest using with
statements handle files (with open(whatever) file:
). see the docs more details.
Comments
Post a Comment