a = random.randint(1, 9999)
name = 'filename' + str(a * 7) + '.txt'
print '>>', a
ROOT = os.path.abspath(os.sep)
filepath = os.path.join(ROOT, name)
os.chdir(filepath)
file = open(filepath, 'w')
显示OSError。 OSError:[Errno 2]没有这样的文件或目录:' / Users / Downloads'
答案 0 :(得分:1)
您正在尝试os.chdir
到文件。您的变量name
是以.txt
结尾的文件名,您要附加到ROOT
。只需在将文件名添加到filepath
变量之前更改目录。
答案 1 :(得分:1)
请删除行os.chdir(filepath),无需更改到目录。使用以下代码。
a = random.randint(1, 9999)
name = 'filename' + str(a * 7) + '.txt'
print '>>', a
ROOT = os.path.abspath(os.sep)
filepath = os.path.join(ROOT, name)
file = open(filepath, 'w')