简体   繁体   English

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

[英]FileNotFoundError when creating a file using a variable in Python 3.5.1

I'm trying to create a file using a variable in Python, but it just won't have it. 我正在尝试使用Python中的变量创建文件,但它只是没有此文件。 Here is the code that creates the filename: 这是创建文件名的代码:

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

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

That is the filename and file extension (.txt). 那就是文件名和文件扩展名(.txt)。 So, I try to create a file using this, using this snippet of code: 因此,我尝试使用此代码段来创建一个文件:

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

(file2a is the contents of a text file called SCORE.txt, this works properly). (file2a是名为SCORE.txt的文本文件的内容,可以正常工作)。

When I execute this code, it gives me an error: 当我执行此代码时,它给我一个错误:

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' 追溯(最近一次通话):文件“ E:\\ Program Files \\ Python guff \\ DocMarker \\ data \\ FinalScore.py”,在file3中的第57行= open(c,“ w +”)FileNotFoundError:[Errno 2]无文件或目录:“ SCORE-(2015/12/28)-(21-05-09).txt”

This is baffling me, as when I changed the "c" bit to "test", it worked. 这让我感到困惑,因为当我将“ c”位更改为“ test”时,它起作用了。 Like this: 像这样:

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

This successfully created a file called "test" that had the contents of SCORE.txt inside of it. 这样成功创建了一个名为“ test”的文件,其中包含SCORE.txt的内容。 I'm baffled as to why it won't work with my "c" variable. 我对为什么它不能与我的“ c”变量一起使用感到困惑。

Because your filename has slashes in it, python is looking for a directory in 由于您的文件名中包含斜杠,因此python在以下目录中查找目录

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

try refactoring your initial code like this: 尝试像这样重构您的初始代码:

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

or, in a more compact and more readable way: 或者,以更紧凑,更易读的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM