python - 在 Python 3.5.1 中使用变量创建文件时出现 FileNotFoundError

标签 python python-3.x

我正在尝试使用 Python 中的变量创建一个文件,但它就是没有。这是创建文件名的代码:

a, b = time.strftime("%d/%m/%Y"), time.strftime("%H-%M-%S")
c = ("SCORE"+"-"+"("+a+")"+"-"+"("+b+")")
c = str(c+".txt")

打印:SCORE-(28/12/2015)-(21-05-09).txt

即文件名和文件扩展名 (.txt)。因此,我尝试使用此代码片段创建一个文件:

file3 = open(c,"w+")
file3.write(file2a)
file3.close()

(file2a 是名为 SCORE.txt 的文本文件的内容,它可以正常工作)。

当我执行这段代码时,它给我一个错误:

Traceback (most recent call last): File "E:\Program Files\Python guff\DocMarker\data\FinalScore.py", line 57, in file3 = open(c,"w+") FileNotFoundError: [Errno 2] No such file or directory: 'SCORE-(28/12/2015)-(21-05-09).txt'

这让我感到困惑,因为当我将“c”位更改为“test”时,它起作用了。像这样:

file3 = open("test", "w+")

这成功地创建了一个名为“test”的文件,其中包含 SCORE.txt 的内容。我很困惑为什么它不适用于我的“c”变量。

最佳答案

因为你的文件名中有斜杠,python正在寻找一个目录

- SCORE-(28
  |
  - 12
    |
    - 2015)-(21-05-09).txt

尝试像这样重构您的初始代码:

a, b = time.strftime("%d-%m-%Y"), time.strftime("%H-%M-%S")
c = ("SCORE"+"-"+"("+a+")"+"-"+"("+b+")")
c = str(c+".txt")

或者,以更紧凑和更易读的方式:

c = time.strftime("SCORE-(%d-%m-%Y)-(%H-%M-%S).txt")

关于python - 在 Python 3.5.1 中使用变量创建文件时出现 FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500870/

相关文章:

python - 为 Mac django-admin 启动 Python 3 的 Django 不工作

python - ThreadPoolExecutor 未定义 [python3]

python - Dash 数据表下载到 Excel

python - 用于 Visual Studio 的 Python 工具上的 Pytest

python - Heroku 在部署时按预期执行 collectstatic?

python - 过滤多维数组

python - 在 CrawlSpider 中将 cookie 传递给后续请求

python-3.x - 权限错误: [WinError 5] Access is denied for creating file

Python 2 与 Python 3 字符串 pickle

python - Django 模型名称不区分大小写,对吗?