2015-11-01 144 views
0

我有一些代碼旨在:創建一個新目錄;要求用戶輸入一些文本來放入文件;創建文件;將文件名和路徑連接在一起,然後將translated中的文本寫入文件中。但是,當我運行下面的代碼,我得到 with open(new_file, 'a') as f: TypeError: invalid file: <_io.TextIOWrapper name='C:\\Downloads\\Encrypted Messages\\hi' mode='w' encoding='cp1252'>嘗試創建/檢查新目錄時出現錯誤

import os 
import os.path 
import errno 

translated = str(input("Please enter your text")) 
encpath = r'C:\Downloads\Encrypted Messages' 

def make_sure_path_exists(encpath): 
    try: 
     os.makedirs(encpath) 
    except OSError as exception: 
     if exception.errno != errno.EEXIST: 
      raise 

name = str(input("Please enter the name of your file ")) 
fullpath = os.path.join(encpath, name) 
new_file = open(fullpath, 'w') 
with open(new_file, 'a') as f: 
    f.write(translated + '\n') 

我也曾嘗試

import os 
import os.path 
import errno 

translated = "Hello World" 
encpath = r'C:\Downloads\Encrypted Messages' 

if not os.path.exists(encpath): 
    os.makedirs(encpath) 
name = str(input("Please enter the name of your file ")) 
fullpath = os.path.join(encpath, name) 
new_file = open(fullpath, 'w') 
with open(new_file, 'a') as f: 
    f.write(translated + '\n') 

我使用Python 3.5.0如果你想知道。

編輯:我改名encpathr'C:\Downloads\EncryptedMessages',我得到一個新的錯誤:FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Downloads\\EncryptedMessages\\justatest'

+0

你不能在with語句之後關閉文件(它已經關閉了,''用'f'調用close來完成',我猜這是錯誤發生的地方?)。第一個代碼不會創建文件夾,因爲您不會調用您創建的例程。 – zeroth

+0

謝謝,在我的代碼中,我沒有指定擴展名有我嗎? – Inkblot

+0

'EncryptedMessages'或'Encrypted Messages'? – itzMEonTV

回答

1

下面的代碼爲我工作-USE raw_input我在2.7

import os 
import os.path 
import errno 

translated = "Hello World" 
encpath = r'C:\Downloads\Encrypted Messages' 

if not os.path.exists(encpath): 
    os.makedirs(encpath) 
name = str(raw_input("Please enter the name of your file ")) 
fullpath = os.path.join(encpath, name) 
new_file = open(fullpath, 'w') 
with open(fullpath, 'a') as f: 
    f.write(translated + '\n') 
    f.close() 
+0

感謝您的幫助 – Inkblot

相關問題