【发布时间】:2017-10-16 21:03:43
【问题描述】:
我编写了一个查询 mongo 数据库并将结果写入文件的代码。 我的代码创建了文件并开始成功在其中写入。但是经过多次迭代(不确定迭代次数是否固定)我得到了 PermissionError。
我已经搜索过它,但我只找到了第一次尝试出错的人的答案,因为他们没有权限。我会准确地说,在执行期间我没有在我的电脑上做任何事情,所以我真的不明白它是怎么发生的。
以下是部分代码:
def query(self, query_date_part, query_actKey_part, filepath):
empty = True
print("0.0 %")
for i in range(len(query_date_part)):
query = {"dt": query_date_part[i], "actKey": query_actKey_part}
cursor = self.collection.find(query)
while cursor.alive:
try:
if empty:
with open(filepath, 'w') as fp:
json.dump(cursor.next(), fp, default=json_util.default)
empty = False
else:
append_to_json(filepath, cursor.next())
except StopIteration:
print("Stop Iteration")
print(str(round(float(i+1) / len(query_date_part) * 100, ndigits=2)) + " %")
return 0
def append_to_json(filepath, data):
"""
Append data in JSON format to the end of a JSON file.
NOTE: Assumes file contains a JSON object (like a Python dict) ending in '}'.
:param filepath: path to file
:param data: dict to append
"""
# construct JSON fragment as new file ending
new_ending = ", " + json.dumps(data, default=json_util.default)[1:-1] + "}\n"
# edit the file in situ - first open it in read/write mode
with open(filepath, 'r+') as f:
f.seek(0, 2) # move to end of file
index = f.tell() # find index of last byte
# walking back from the end of file, find the index
# of the original JSON's closing '}'
while not f.read().startswith('}'):
index -= 1
if index == 0:
raise ValueError("can't find JSON object in {!r}".format(filepath))
f.seek(index)
# starting at the original ending } position, write out
# the new ending
f.seek(index)
f.write(new_ending)`
部分输出:
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
注意:在执行过程中文件的大小会增加。当它崩溃时大约是 300 个月,我的硬盘驱动器上还有很多空间,但文件的大小可能是个问题?
配置:我使用的是 Windows 7、Python 3.6,我的 IDE 是 PyCharm Community Edition 2016.3.2
【问题讨论】:
-
使用“with open...”应该关闭文件。有可能不是吗?
-
您确定
append_to_json正在执行多次吗?似乎是在else条件下 -
@itzMEonTV if else 只是在第一次迭代时重新创建文件然后 append_to_json 被执行多次(我确信因为文件的大小在执行过程中会增加)
-
在 Windows 中,默认情况下,当一个进程打开一个文件时,它会以独占方式打开它——没有其他人可以打开该文件。所以只有一个给定文件的打开。您看到的症状表明锁定尚未被关闭的文件清除。因此,我会查看您的代码以查找可能导致该问题的原因。
-
更改设计。在
query中,不是为光标中的每个元素打开和关闭文件,而是先打开文件,然后从光标开始添加元素。或者,如果内存允许,在内存中构建整个 json 并在最后写入文件。
标签: python python-3.x permissions