2016-02-15 676 views
0

當我將這段代碼寫入一個可執行文件時,寫入文件的功能起作用,但它寫入了一個隨機目錄。我不知道如何讓它寫入我的桌面,就像它是一個普通的python文件時一樣。如何在python中將文件寫入桌面?

這裏是我的代碼,

def write(): 
     print('Creating a new file') 

     name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt 

     try: 
      file = open(name,'w') # Trying to create a new file or open one 
      file.close() 

     except: 
      print('Something went wrong! Cannot tell what?') 
      sys.exit(0) # quit Python 
+1

指定文件的完整路徑 – SirParselot

+0

如果未另外指定,Python將寫入當前目錄。 –

+0

「桌面」取決於您的操作系統和/或窗口管理器。 – chepner

回答

1

您需要指定要保存的路徑。此外,請使用os.path.joindocumentation)將路徑和文件名放在一起。你可以這樣做:

from os.path import join 
def write(): 
     print('Creating a new file') 
     path = "this/is/a/path/you/want/to/save/to" 
     name = raw_input('Enter a name for your file: ')+'.txt' # Name of text file coerced with +.txt 

     try: 
      file = open(join(path, name),'w') # Trying to create a new file or open one 
      file.close() 

     except: 
      print('Something went wrong! Cannot tell what?') 
      sys.exit(0) # quit Python 
0

它不寫入隨機目錄。它正在寫入當前目錄,即從中運行它的目錄。如果您希望它寫入特定目錄(如桌面),則需要將路徑添加到文件名或切換當前目錄。首先是與

 
name = os.path.join('C:\Users\YourUser\Desktop', name) 

二是所做的一切與

 
os.chdir('C:\Users\YourUser\Desktop') 

或任何路徑到桌面是。

+0

您可能還想檢查用戶是否已將路徑信息附加到輸入中的文件名,例如,如果有人在提示符下輸入「C:\ Windows \ System32 \ rundll.exe」。 –

相關問題