为什么我拒绝解决 Python IOError: [Errno 13] 写信给文件?

我无法理解我做错了什么。 我花了一些测试并将结果写下给文件。 写入文件的代码的一部分如下 /在课堂叫 Tester/:


@staticmethod
def printHeader/resultsFileName/:
if not os.path.isfile/resultsFileName/:
# The file does not exist, thus
# we need to print the header

# Opens the results file
with open/resultsFileName,"a"/ as file:
# Prints the header
file.write/"A long header"/


@staticmethod
def printResults/resultsFileName,otherArguments/:

# Prints the header if it does not exist
Tester.printHeader/resultsFileName/

# Prints the results
with open/resultsFileName,"a"/ as file:

file.write/otherArguments/


有时我收到此错误:


Traceback /most recent call last/:
File "main.py", line 74, in <module>
File "tester.py", line 88, in methodOne
File "tester.py", line 441, in printResults
File "tester.py", line 428, in printHeader
IOError: [Errno 13] Permission denied: 'results.txt'


而在其他情况下,一切顺利。 我无法理解问题是什么。 有任何想法吗?

笔记

1 : 我有许可
rwx

在记录文件的目录上。

笔记

2 : 在已经记录了几行结果之后发生错误。 因此,当代码检查标题是否应打印而发生这种情况 /但他不应该打印它,因为文件存在/.

UPDATE 1

:

正如假设的那样,我更改了我的代码以避免多个打开和关闭文件。 现在他在一帧中写下了所有内容。 这是一个更新的代码:


@staticmethod
def printResults/resultsFileName,otherArguments/:

# Prints the header if it does not exist
if not os.path.exists/resultsFileName/:

# The file does not exist, thus
# we need to print the header

# Opens the results file
# HERE IS WHERE ERRNO 13 HAPPENS
# STRANGELY, THE FILE DOES EXIST
# AS SEVERAL LINES OF RESULTS
# HAVE ALREADY BEEN WRITTEN
with open/resultsFileName,"w"/ as file:

# Prints the header
file.write/"A suitable header"/
# Prints the results
file.write/otherArguments/
else:

# Prints the results
with open/resultsFileName,"a"/ as file:
file.write/otherArguments/


看起来
os.path.exists//

在某些时候回归
FALSE

, 即使文件真的存在。 可能有一些叫我写权限的东西 /也许文件在录制后不正确关闭?/.

在解释中
os.path.exists//

它说:

在某些平台上,此功能可以返回 False, 如果不允许许可 os.stat// 在所请求的文件中,即使路径身体存在。

UPDATE 2

我将代码更改为避免下一步
os.path.isfile//

:


# Opens the results file 
with open/resultsFileName,"a"/ as file:
if file.tell// == 0:
# Prints the header
file.write/"Header"/
# Prints the results
file.write/otherArguments/
file.close//
else:

# Prints the results
file.write/otherArguments/
file.close//


尽管如此, ERRNO 13 发生在
with open/resultsFileName,"a"/ as file:

.
我有许可
rw

两者均在发生错误之前写入多行的文件中。 OS是 Linux.
</module>
已邀请:

八刀丁二

赞同来自:

os.path.isfile/path/

回报 True, 如果一个
path

有一个文件 AND 你有 /至少/ 权利对他来说。 IOW, 他回来了 False, 如果一个
path

有,但是目录和/或者你对他没有权利。 所以你的测试从一开始就是错误的 -
os.path.exists//

将是最好的选择。 但在任何情况下:这些操作不是原子的,所以可以在检查其存在的时刻之间创建文件,以及当您尝试打开它时的时刻,因此整个设计实际上是不安全的。 此外,说明打开并关闭文件 - 这些都是昂贵的操作,所以我建议 - 如果有可能,重新考虑所有设计,只能打开文件一次并在完成后关闭它。

卫东

赞同来自:

尝试关闭文件 result.txt 在开始计划之前 /我会打开它/.

检查录制权限。

另一个原因可以是文件条目 .txt 在没有这些权限的目录中。 尝试运行 python 从指定的目录。

要回复问题请先登录注册