如何使用with open() as f: ...在不存在的目录中写入文件.
例如:
with open('/Users/bill/output/output-text.txt', 'w') as file_to_write:
file_to_write.write("{}\n".format(result))
Run Code Online (Sandbox Code Playgroud)
假设该/Users/bill/output/目录不存在.如果目录不存在,只需创建目录并在那里写入文件.
我想检查路径中是否存在名为“输出文件夹”的文件夹
D:\LaptopData\ISIS project\test\d0_63_b4_01_18_ba\00_17_41_41_00_0e
如果名为“输出文件夹”的文件夹不存在,则在那里创建该文件夹。
任何人都可以帮忙提供解决方案吗?
目前,我有以下代码......
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()
Run Code Online (Sandbox Code Playgroud)
我的目标是让python将文件(在file_name下)写入当前目录(IE中保存python脚本的IE)的"address"文件夹中的文件中.
我查看了os模块,但我不想更改当前目录,这些目录尚不存在.
在这个有趣的威胁中,如果目录不存在,用户会提供一些创建目录的选项。
得票最多的答案显然是最受欢迎的,我猜是因为它是最短的方法:
if not os.path.exists(directory):
os.makedirs(directory)
Run Code Online (Sandbox Code Playgroud)
第二个答案中包含的功能似乎更强大,在我看来这是最好的方法。
import os
import errno
def make_sure_path_exists(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
Run Code Online (Sandbox Code Playgroud)
所以我想知道,人们在他们的脚本中做什么?键入 2 行只是为了创建一个文件夹?或者更糟糕的是,将函数复制并粘贴make_sure_path_exists到需要创建文件夹的每个脚本中?
我希望像 Python 这样广泛传播的编程语言已经有一个包含类似功能的库。
我所知道的其他 2 种编程语言更像是脚本语言,可以轻松做到这一点。
重击: mkdir -p path
电源外壳: New-Item -Force path
请不要将此问题视为对 Python 的咆哮,因为它不是那样的。
我打算学习 Python 来编写脚本,其中 90% 的时间我都必须创建文件夹,我想知道这样做的最有效方法是什么。
我真的认为我缺少关于 Python 的一些东西。
所以我希望它独立于使用代码的计算机,所以我希望能够在当前目录中创建一个目录并将我的绘图保存到该新文件中.我看了一些其他的问题并试了一下(我有两次尝试,一次注释掉):
import os
from os import path
#trying to make shift_graphs directory if it does not already exist:
if not os.path.exists('shift_graphs')
os.mkdirs('shift_graphs')
plt.title('Shift by position on '+str(detector_num)+'-Detector')
#saving figure to shift_graphs directory
plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector'))
print "plot 5 done"
plt.clf
Run Code Online (Sandbox Code Playgroud)
我收到错误:
AttributeError: 'module' object has no attribute 'mkdirs'
Run Code Online (Sandbox Code Playgroud)
我也想知道我在目录中保存它的想法是否有效,我无法测试,因为我在上面的部分中遇到了错误.
我想知道你是否有人创建了一个在给定路径中创建文件夹的功能.
例如:NewFolder = ['/ projects/Resources/backup_Folder']
我对 python 很陌生,所以我需要一些帮助。我想创建一个代码来检查是否创建了具有给定名称的文件夹,如果没有,则创建它,如果存在,则转到它并在其中检查是否存在另一个具有给定名称的文件夹,如果没有,它创造了它。在我的代码中,我不知道如何转到已存在或刚刚创建的文件夹并重复 IF。
import os
MYDIR = ("test")
CHECK_FOLDER = os.path.isdir(MYDIR)
if not CHECK_FOLDER:
os.makedirs(MYDIR)
print("created folder : ", MYDIR)
else:
print(MYDIR, "folder already exists.")
Run Code Online (Sandbox Code Playgroud) 我试图从 python 3 中的文件名列表中创建一组随机文件。
#!/usr/local/bin/python3
import random
import sys
random.seed()
print("Reading lines from ", sys.argv[1])
linecount = 0
lines = []
with open(sys.argv[1]) as f:
for line in f:
lines.append(line)
filelist = random.sample(lines, 5);
for newfile in filelist:
print("Touching file ", newfile)
open(newfile.rstrip(), "a+")
Run Code Online (Sandbox Code Playgroud)
对于第一个文件,这总是失败:
$ : ./file-gen.py files.txt
Reading lines from files.txt
Touching file 62/6226320DE.pdf
Traceback (most recent call last):
File "./file-gen.py", line 19, in <module>
open(newfile.rstrip(), "a+");
FileNotFoundError: [Errno 2] No such file or directory: '62/6226320DE.pdf'
Run Code Online (Sandbox Code Playgroud)
任何想法缺少什么?
我正在django创建一个视频共享网站.
目前,如果用户注册并上传视频,则会将其上传到media/vid/uploaded-vid.然后我使用ffmpeg转换为flv.我想做的是:
用户名为alex1的人注册,我想在确认他的电子邮件时为他创建一个目录/media/vid/members-vid/alex1
如果他上传了一个视频,它将被转换为flv media/vid/uploaded-vid然后复制到/media/vid/members-vid/alex1.视频输入media/vid/uploaded-vid应该被删除.
我想保证/media/vid/.你如何保护django目录?或者只是一个阿帕奇chmod?
我想知道我是否可以使用celery/rabbitqm将文件从一个文件夹复制到另一个文件夹,或者创建新文件夹.
这只是一个关于哪一个更"pythonic"的问题
使用if:
import os
somepath = 'c:\\somedir'
filepath = '%s\\thefile.txt' % somepath
if not os.path.exists(somepath) and not os.path.isfile(filepath):
os.makedirs(somepath)
open(filepath, 'a').close
else:
print "file and dir allready exists"
Run Code Online (Sandbox Code Playgroud)
或使用try/Except:
import os
somepath = 'c:\\somedir'
filepath = '%s\\thefile.txt' % somepath
try:
os.makedirs(somepath)
except:
print "dir allready exists"
try:
with open(filepath):
// do something
except:
print "file doens't exist"
Run Code Online (Sandbox Code Playgroud)
正如你在上面的例子中看到的那样,哪一个在python上会更正确?另外,在哪些情况下我应该使用try/except而不是if/else?我的意思是,我应该替换所有我的if/else测试来尝试/除外吗?
提前致谢.
python ×10
directory ×2
django ×1
django-1.3 ×1
file ×1
io ×1
python-2.7 ×1
python-3.x ×1
rss ×1
subdirectory ×1