问题描述
当前,我有以下代码...
Currently, I have the following code...
file_name = content.split('=')[1].replace('"', '') #file, gotten previously
fileName = "/" + self.feed + "/" + self.address + "/" + file_name #add folders
output = open(file_name, 'wb')
output.write(url.read())
output.close()
我的目标是让python将文件(在file_name下)写入当前目录(即python脚本所在的目录)"feed"文件夹中"address"文件夹中的文件中.
My goal is to have python write the file (under file_name) to a file in the "address" folder in the "feed" folder in the current directory (IE, where the python script is saved)
我已经研究了os模块,但是我不想更改我的当前目录,并且这些目录还不存在.
I've looked into the os module, but I don't want to change my current directory and these directories do not already exist.
推荐答案
首先,我不是100%确信我理解这个问题,所以让我说一下我的假设:1)您要写入尚不存在的目录中的文件.2)路径是相对的(相对于当前目录).3)您不想更改当前目录.
First, I'm not 100% confident I understand the question, so let me state my assumption:1) You want to write to a file in a directory that doesn't exist yet.2) The path is relative (to the current directory).3) You don't want to change the current directory.
因此,鉴于:检查以下两个函数:os.makedirs和os.path.join.由于您要指定相对路径(相对于当前目录),因此您不想添加初始的"/".
So, given that:Check out these two functions: os.makedirs and os.path.join. Since you want to specify a relative path (with respect to the current directory) you don't want to add the initial "/".
dir_path = os.path.join(self.feed, self.address) # will return 'feed/address'
os.makedirs(dir_path) # create directory [current_path]/feed/address
output = open(os.path.join(dir_path, file_name), 'wb')
这篇关于在不更改目录的情况下用Python写入新目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!