Creating/Using 文件 Python 3.6

Creating/Using Files with Python 3.6

我正在尝试制作一些可以生成多个随机文件的东西,并根据这些文件确定发生的结果(基于文本的冒险游戏),是的,我想使用文件,因为游戏应该是这样的成为 'hack-able/mod-able.' 出于某种原因,尝试在另一个目录中创建文件时出现错误

FileNotFoundError: [Errno 2] No such file or directory: 'file0599265.txt'

import os
import os.path
import random as rand
os.chdir("C:\Program Files (x86)\File Stuff")
f = open('file' + str(rand.randint(1,1000000)) + '.txt', 'w')
f.write('Test')
f.close

我必须做什么才能创建该文件?我真的无法确定谁更改目录的事情以使其位于我想要的位置,但我现在会坚持这样做("C:\Program Files (x86)\File Stuff" 仅用于测试目的)。

尽量把文件写到你确定有写权限的地方,比如你家的子文件夹:C:\Users\YOUR_USERNAME.

我没问题运行你的代码,在C:\Program Files (x86)\

之外

4 个问题:

  1. 您没有导入 random 这会导致错误
  2. 您应该使用 with 关键字,因为在这种情况下使用它是非常标准的
  3. 必须已经创建了目录C:\Program Files (x86)\File Stuff
  4. 您需要将 \ 更改为 \\是一个转义字符,所以如果你不转义转义,那么它可以运行发生冲突(即\n)。

事不宜迟,这是新代码:

import os, os.path, random
os.chdir("C:\Program Files (x86)\File Stuff")
with open('file' + str(random.randint(1,1000000)) + '.txt', 'w') as f:
    f.write('Test')