创建目录Python

2024-09-27 09:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的指导老师提供了以下代码,但当从命令行运行时,它在OSX上不起作用。在

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
fout = open(file_name, 'w')

错误消息:

^{pr2}$

在我进入这个类之前,我一直在编写Python,在做了一些研究之后,它认为您需要导入os模块来创建一个目录。在

然后可以指定要在该目录中创建文件。在

我相信在访问文件之前,您可能还需要切换到该目录。在

我可能错了,我想知道我是否错过了另一个问题。在


Tags: 文件ofthe代码命令行name目录input
2条回答

正如@Morgan Thrapp在评论中所说,open()方法不会为您创建文件夹。在

如果文件夹/data/已经存在,它应该可以正常工作。在

否则你必须check if the folder exists,如果不是,那么{}

import os 

if not os.path.exists(directory):
    os.makedirs(directory)

所以。。您的代码:

^{pr2}$

变成这样:

import os

folder = 'data/'

if not os.path.exists(folder):
    os.makedirs(folder)

filename = raw_input('Enter the name of your file: ')

file_path = folder + filename + '.txt'

fout = open(file_path, 'w')

检查文件夹“data”是否不存在。如果不存在,则必须创建它:

import os

file_name = 'data/' + raw_input('Enter the name of your file: ') + '.txt'
if not os.path.exists('data'):
    os.makedirs('data')
fout = open(file_name, 'w')

相关问题 更多 >

    热门问题