2015-03-31 52 views
-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() 
+0

你可以使用'os.path.join'來將你的'files'文件夾的路徑添加到輸入文件名。 – 2015-03-31 20:22:55

+0

如何以及在哪裏使用它?我以前從來沒有使用過'os',只是在使用清晰屏幕時才用過,但那就是它。 – VirtualHat 2015-03-31 20:25:20

+0

抱歉,您應該首先查找https://python.org上的文檔。 – 2015-03-31 20:27:49

回答

2

如果你不想filename被認爲是相對於當前的工作目錄,你要轉變成一個在將其傳遞到open之前更具體的絕對路徑。使用os.path.join到一個目錄名和文件名獨立於平臺的方式結合在一起:

directory = "/media/GENERAL/Projects/files" 
filename = input("Plese enter a file name.") 
file = open(os.path.join(directory, filename), "w") 

無關的這個問題,但涉及的代碼相同的部分,我建議使用with語句來處理你的文件(with open(whatever) as file:)。有關更多詳細信息,請參閱the docs