2016-11-06 28 views
2

我正在創建一個非常基本的python程序,它允許用戶輸入一個然後作爲代碼運行的命令。爲什麼exec()命令運行時沒有錯誤但沒有產生預期的輸出?

例如,我已經導入了一個名爲textScripts.py的文件:在該文件中有一個名爲createFile()的函數。當用戶輸入textScripts.createFile()時,它被傳遞到exec()。它運行時沒有錯誤並退出程序,但文件未創建!

我知道createFile()功能的作品,因爲如果我把textScripts.createFile()在代碼中創建一個文件。

這裏是代碼中的相關片段:

commandList=[] 
while(commandRun): 
    count = 0 
    commandList.append(input(">>>")) 
    exec(commandList[count]) 
    print(commandList[count]) 
    count += 1 

here is a screenshot of the code being run:

>>> textScripts.createFile() 
>>> 

here is a screenshot of the folder:

__pyCache__ 
textScripts.py 
CLIFile.py 

應該有一個文件,此文件夾中

這裏是功能createFile()

def createFile(
    destination = os.path.dirname(__file__), 
    text = "Sick With the Python\n" 
    ): 
    ''' createFile(destination, text) 

     This script creates a text file at the 
     Specified location with a name based on date 
    ''' 
    date = t.localtime(t.time()) 
    name = "%d_%d_%d.txt" %(date[1], date[2], date[0]) 

    if not(os.path.isfile(destination + name)): 
     f = open(destination + name, "w") 
     f.write(text) 
     f.close 
    else: 
     print("file already exists") 

我提前道歉,如果這是一個明顯的問題;我是python的新手,並且一直在尋找幾個小時來回答爲什麼發生這種情況。

+0

您可以複製什麼的截圖說和文件夾結構的問題,而不是鏈接到他們?截圖是不可能讀取的,在問題中提供信息會很好。 –

+0

還提到你正在通過'input()'傳遞什麼,沒有那個人怎麼能幫助你? –

+0

@EliSadoff是的我可以 –

回答

1

文件保存到錯誤的文件夾(你可以將 「打印(目的地+名)」,在你的函數)

您需要更換此:

destination + name 

這樣:

os.path.join(destination, name) 

PS:

  1. 你不CL ose該文件(f.close - > f.close())
  2. 打開任何資源的最佳方式是使用「with」。

例如:

with open('file.txt', 'w') as f: 
    f.write('line') 
+0

謝謝! –

相關問題