尝试创建/检查新目录时出错

时间:2015-11-01 14:07:13

标签: python path directory

我有一些代码用于:创建一个新目录;要求用户输入一些文本放入文件中;创建文件;将文件名和路径连接在一起,然后将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,以防你想知道。

编辑:我已将encpath重命名为r'C:\Downloads\EncryptedMessages'并收到新错误:FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Downloads\\EncryptedMessages\\justatest'

1 个答案:

答案 0 :(得分: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()
相关问题