2015-11-01 110 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

相关问题