python - Python - ValueError: I/O Operation on Closed File Error
问题描述
Code:
if numberofscreenshots == "1":
# Read the data in the template file.
with open('path/to/json/file','r') as f:
data = f.read()
data = json.loads(data)
# Check the data before.
data['tabs'][0]['views'][1]['screenshots']
# Overwrite screenshots placeholders.
data['tabs'][0]['views'][1]['screenshots'] = data['tabs'][0]['views'][1]['screenshots'][0]
# Check after to make sure it worked.
data['tabs'][0]['views'][1]['screenshots']
# Write data to JSON file.
with open('path/to/json/file', 'w') as f:
f.write(json.dumps(data))
else:
print("Something went wrong.")
The code above works fine until I add this somewhere into it:
screenshotplaceholdertext = {"Package Screenshot URL 1":screenshoturl1}
for removescreenshotplaceholders in f:
for screenshotplaceholder, removescreenshotplaceholder in screenshotplaceholdertext.items():
removescreenshotplaceholders = removescreenshotplaceholders.replace(screenshotplaceholder, removescreenshotplaceholder)
f.write(removescreenshotplaceholders)
Full Code:
if numberofscreenshots == "1":
# Read the data in the template file.
with open('path/to/json/file','r') as f:
data = f.read()
screenshotplaceholdertext = {"Package Screenshot URL 1":screenshoturl1}
for removescreenshotplaceholders in f:
for screenshotplaceholder, removescreenshotplaceholder in screenshotplaceholdertext.items():
removescreenshotplaceholders = removescreenshotplaceholders.replace(screenshotplaceholder, removescreenshotplaceholder)
data = json.loads(data)
# Check the data before.
data['tabs'][0]['views'][1]['screenshots']
# Overwrite screenshots placeholders.
data['tabs'][0]['views'][1]['screenshots'] = data['tabs'][0]['views'][1]['screenshots'][0]
# Check after to make sure it worked.
data['tabs'][0]['views'][1]['screenshots']
# Write data to JSON file.
with open('path/to/json/file', 'w') as f:
f.write(json.dumps(data))
f.write(removescreenshotplaceholders)
else:
print("Something went wrong.")
If I try and run this code I get a error: ValueError: I/O operation on closed file so any help will be welcomed.
解决方案
你的问题就在这里:
with open('path/to/json/file','r') as f:
data = f.read()
# f is closed upon leaving the scope of the "with" block
screenshotplaceholdertext = {"Package Screenshot URL 1":screenshoturl1}
# Here, you try to use the file ... but it's closed.
for removescreenshotplaceholders in f:
我认为你想要做的是循环data
,而不是f
......你已经从文件中读取了,不是吗?
推荐阅读
- python - Python/Bloomberg API - 动态安全屏幕
- python - 用于 Visual Studio 的类似 Jupyter 的 Markdown
- c - 评估文件的权限位
- arrays - JSX 呈现一个字母初始按钮,其中包含一组以相同字母开头的按钮
- node.js - Parse Json 在字段中返回 - 字符
- typescript - 为什么我无法打开带有打字稿伪造链接的文件对话框
- reactjs - 转换路由(页面)时状态重置
- python - Python Pyinstaller ERRNO 22 无效参数
- java - 根据值在 keySet() 上放置条件 - HashMap --> 流到 ArrayList
- javascript - 将 onclick 函数共享到按钮组件 React JS