Код: Выделить всё
@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
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. Ошибка возникает после того, как уже записано несколько строк результатов. Таким образом, это происходит, когда код проверяет, следует ли печатать заголовок или нет (но он не должен его печатать, поскольку файл существует).
ОБНОВЛЕНИЕ 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.stat() для запрошенного файла, даже если путь физически существует.
ОБНОВЛЕНИЕ 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()
У меня есть разрешения rw как на папку, так и на файл, в котором до возникновения ошибки написано несколько строк. ОС — Linux.
Подробнее здесь: https://stackoverflow.com/questions/545 ... -to-a-file