2013-05-07 77 views
0

好吧,我基本上正在編寫一個程序來創建文本文件,但我希望它們在與.py文件可能位於同一文件夾中的文件夾中創建。我該怎麼做? 使用Python 3.3在本地目錄中創建一個python文件

+0

可能會有幫助嗎? http://stackoverflow.com/questions/3918433/what-is-the-python-equivalent-of-unix-touch – squiguy 2013-05-07 23:32:25

回答

0

使用open

open("folder_name/myfile.txt","w").close() #if just want to create an empty file 

如果你想創建一個文件,然後用它做什麼,那麼最好使用with聲明:

with open("folder_name/myfile.txt","w") as f: 
    #do something with f 
+2

應該使用上下文管理器這樣的事情。 – 2013-05-07 23:41:32

+0

做'open(filename,'w')。close()'會截斷文件,如果文件已經存在並且有任何內容。使用'open(filename,'a')。close()'更安全。 – 2013-07-23 03:07:25

5

爲了找到腳本所在目錄:

import os 

path_to_script = os.path.dirname(os.path.abspath(__file__)) 

然後你可以使用它作爲你的文件的名字:

my_filename = os.path.join(path_to_script, "my_file.txt") 

with open(my_filename, "w") as handle: 
    print("Hello world!", file=handle) 
+1

+1。但值得指出的是,在完成可能改變工作目錄的任何內容之後,你不能相信'__file__'。如果你不確定這意味着什麼,那麼做一下這個例子的功能,調用'abspath',並在最開始時將它保存在一個變量中,然後再使用該變量。 – abarnert 2013-05-08 00:55:18

+0

另外,'print >>句柄,「Hello world!」是一個'SyntaxError'。 OP使用Python 3.3。試試'print(「Hello world!」,file = handle)''。 – abarnert 2013-05-08 00:55:54

+0

確實。更新。 – rakslice 2013-05-08 01:08:57

相關問題