Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PermissionError:[Errno 13]权限被拒绝(在文件中多次成功写入尝试后)_Python_Python 3.x_Permissions - Fatal编程技术网

Python PermissionError:[Errno 13]权限被拒绝(在文件中多次成功写入尝试后)

Python PermissionError:[Errno 13]权限被拒绝(在文件中多次成功写入尝试后),python,python-3.x,permissions,Python,Python 3.x,Permissions,我编写了一个查询mongo数据库并将结果写入文件的代码。 我的代码创建了文件并成功地开始写入它。但经过多次迭代(不确定迭代次数是否固定)后,我得到了一个许可错误 我已经搜索过了,但是我只找到了关于那些在第一次尝试时出错的人的答案,因为他们没有权限。我将明确指出,在执行过程中,我没有在我的计算机上做任何事情,因此我真的不明白它是如何发生的 以下是部分代码: 6.75 % Stop Iteration 6.76 % Traceback (most recent call last): Fil

我编写了一个查询mongo数据库并将结果写入文件的代码。 我的代码创建了文件并成功地开始写入它。但经过多次迭代(不确定迭代次数是否固定)后,我得到了一个许可错误

我已经搜索过了,但是我只找到了关于那些在第一次尝试时出错的人的答案,因为他们没有权限。我将明确指出,在执行过程中,我没有在我的计算机上做任何事情,因此我真的不明白它是如何发生的

以下是部分代码:

6.75 %
Stop Iteration
6.76 %
Traceback (most recent call last):
    File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 237, in <module>
        mdbc.query(split_date(2017,5,6,1,0,2017,5,16,10,0,step=2), {"$in": ["aFeature"]}, 'test.json')
    File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 141, in query
        append_to_json(filepath, cursor.next())
    File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 212, in append_to_json
        with open(filepath, 'r+') as f:
PermissionError: [Errno 13] Permission denied: 'test.json'
Process finished with exit code 1
def查询(self、query\u date\u part、query\u actKey\u part、filepath):
空=真
打印(“0.0%”)
对于范围内的i(len(查询日期部分)):
query={“dt”:query\u date\u part[i],“actKey”:query\u actKey\u part}
cursor=self.collection.find(查询)
cursor.alive时:
尝试:
如果为空:
打开(文件路径“w”)作为fp:
dump(cursor.next(),fp,default=json_util.default)
空=假
其他:
将\u追加到\u json(文件路径,cursor.next())
除停止迭代外:
打印(“停止迭代”)
打印(str(圆形(浮动(i+1)/len(查询日期部分)*100,NDIGTS=2))+“%”)
返回0
def append_to_json(文件路径,数据):
"""
将JSON格式的数据追加到JSON文件的末尾。
注意:假设文件包含以“}”结尾的JSON对象(如Python dict)。
:param filepath:文件的路径
:param data:dict to append
"""
#将JSON片段构造为新文件结尾
new_ending=“,”+json.dumps(数据,默认值=json_util.default)[1:-1]+“}\n”
#就地编辑文件-首先以读/写模式打开它
将open(文件路径“r+”)作为f:
f、 查找(0,2)#移动到文件末尾
index=f.tell()#查找最后一个字节的索引
#从文件末尾往回走,找到索引
#原始JSON的结尾“}”
而不是f.read().startswith('}'):
索引-=1
如果索引==0:
raise VALUERROR(“在{!r}中找不到JSON对象”。格式(文件路径))
f、 搜索(索引)
#从原始结束}位置开始,写出
#新结局
f、 搜索(索引)
f、 写(新的结尾)`
部分输出:

6.75 %
Stop Iteration
6.76 %
Traceback (most recent call last):
    File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 237, in <module>
        mdbc.query(split_date(2017,5,6,1,0,2017,5,16,10,0,step=2), {"$in": ["aFeature"]}, 'test.json')
    File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 141, in query
        append_to_json(filepath, cursor.next())
    File "C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py", line 212, in append_to_json
        with open(filepath, 'r+') as f:
PermissionError: [Errno 13] Permission denied: 'test.json'
Process finished with exit code 1
6.75%
停止迭代
6.76%
回溯(最近一次呼叫最后一次):
文件“C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py”,第237行,在
mdbc.query(split_date(2017,5,6,1,02017,5,16,10,0,step=2),{“$in”:[“aFeature”]},'test.json')
文件“C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py”,第141行,在查询中
将\u追加到\u json(文件路径,cursor.next())
文件“C:/Users/username/PycharmProjects/mongodbtk/mquerytk.py”,第212行,附在json之后
将open(文件路径“r+”)作为f:
PermissionError:[Errno 13]权限被拒绝:“test.json”
进程已完成,退出代码为1
注意:文件的大小在执行过程中会增加。当它崩溃时,大约是300个月,我的硬盘上仍然有很多空间,但文件的大小可能是一个问题


配置:我使用Windows 7、Python 3.6,我的IDE是PyCharm Community Edition 2016.3.2

您的文件位于程序无法访问的位置。尝试将其移动到其他目录。或者可能是您输入了错误的文件路径。我希望这对你有用

试试这个

except StopIteration:
    if not fp.closed: fp.close()
    print("Stop Iteration")

我也遇到了同样的问题,在测试之后,似乎在试图太“频繁”地写入同一个文件时会出现一些“错误”,每秒钟多次。我将提供一个非常小的代码片段,您可以使用它进行测试:

import csv

text = "dfkjghdfkljghflkjghjkdfdfgsktjgrhsleiuthsl uirghuircbl iawehcg uygbc sgygerh"
FIELD_NAMES = ['asd', 'qwe']


with open('test.txt', 'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=FIELD_NAMES)
    writer.writeheader()

max = 10000
i = 0

while i <= max:
    print(str(i))
    with open('test.txt', 'a', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=FIELD_NAMES)
        rowData = {'asd': text, 'qwe': text}
        writer.writerow(rowData)
    i += 1
导入csv
text=“DFKJGHDFKLJGHFLKJGHJKKDFDFGSKTJGRHSLEIUTHSL uirghuircbl iawehcg UIBBC SGYGER”
字段名称=['asd','qwe']
打开('test.txt','w',换行符='')作为csvfile:
writer=csv.DictWriter(csvfile,fieldnames=FIELD\u name)
writer.writeheader()
最大值=10000
i=0

而我这似乎是一种竞赛条件。创建一个helper函数,它执行的任务与引发竞争条件的函数相同,这对我来说是可行的。 例如,如果一个代码块或函数a()正在创建竞争条件,那么我们可以通过再次调用另一个辅助函数a_helper()来处理此异常,该函数也会执行相同的操作。 python代码示例:

try:
   A()
except PermissionError:
   # Do something
else:
   A_helper()

使用“打开…”应关闭文件。有可能不是吗?你确定
append\u to\u json
正在执行多次吗?似乎是在
else
condition@itzMEonTVif-else只是在第一次迭代时重新创建文件,然后在windows中多次执行append_to_json(我确信,因为文件的大小在执行过程中会增加),默认情况下,当一个进程打开一个文件时,它以独占方式打开该文件——其他任何人都无法打开该文件。因此,只需打开一个给定文件。您看到的症状表明,关闭的文件未清除锁。所以我会看看你的代码,看看是否有可能导致这种情况。改变设计。在
query
中,不要为游标中的每个元素打开和关闭文件,而是先打开文件,然后开始从游标添加元素。或者,如果内存允许,在内存中构建整个json,并在最后写入文件。该文件是由该程序创建的,并且在引发此错误之前已在其中写入多次。计算机中是否有任何函数不允许python访问太大的文件?我不确定我是否很好地理解您希望如何使用此代码。我发布了很多没有很好注释的代码,所以可能这不是你的意思?不,它不起作用。顺便说一句,我真的不明白你为什么在迭代中写这个。是