-2
我的python項目有2個文件。我創建了一個名爲files
的文件夾,因此當用戶在文本編輯器中寫入內容時,它將其保存到該文件夾中,然後當用戶打開文本查看器時,他們鍵入該文件名並在files
目錄中查找它。我將如何能夠做到這一點?如何讓Python在不同的位置保存文件?
代碼的文本編輯器:
def edit():
os.system('cls' if os.name == 'nt' else 'clear')
print ("EDIT")
print ("-------------")
print ("Note: Naming this current document the same as a different document will replace the other document with this one.")
filename = input("Plese enter a file name.")
file = open(filename, "w")
print ("FILE: " +filename+".")
lines = get_lines()
file.write('\n'.join(lines))
def get_lines():
print("Enter 'stop' to end.")
lines = []
line = input()
while line != 'stop':
lines.append(line)
line = input()
return lines
文本查看器代碼:
def textviewer():
os.system('cls' if os.name == 'nt' else 'clear')
print ("Text Viewer.")
file_name = input("Enter a text file to 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 you like to edit it? (y for yes, n for no)")
if edit_text == "y":
file = open(file_name, "w")
print ("You are now in edit mode.")
lines = get_lines
file.write('\n'.join(lines))
time.sleep(2)
if edit_text == "n":
print ("Press enter to exit")
input()
你可以使用'os.path.join'來將你的'files'文件夾的路徑添加到輸入文件名。 – 2015-03-31 20:22:55
如何以及在哪裏使用它?我以前從來沒有使用過'os',只是在使用清晰屏幕時才用過,但那就是它。 – VirtualHat 2015-03-31 20:25:20
抱歉,您應該首先查找https://python.org上的文檔。 – 2015-03-31 20:27:49