python - 使用 Python 3.6 创建/使用文件

标签 python python-3.6

我正在尝试制作一些可以生成多个随机文件的东西,并根据这些文件确定发生的结果(基于文本的冒险游戏),是的,我想使用文件,因为游戏应该是“可破解/可修改。”由于某种原因,尝试在另一个目录中创建文件会出现错误

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”仅用于测试目的)。

最佳答案

4 个问题:

  1. 您没有导入随机,这会导致错误
  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')

关于python - 使用 Python 3.6 创建/使用文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158368/

相关文章:

python - Selenium 在 Python 中不起作用

python - 让不和谐的机器人每 10 秒改变一次播放状态

python - 在 python 中运行时将数据从 GUI 传递到线程

pycrypto - 在python 3.6中安装pycrypto的问题

python - Python中的多行f字符串

python - quit 函数在 try-except block 中不起作用

python - 使 python reload() 函数从 .py 而不是 .pyc 读取

python - 将 2D 数组 reshape 为 3D 数组以进行 tiff 转换

python - 用 Python 编写 Windows 迷你转储

python - 网络米科 : enable a cisco device