Python-ValueError:关闭文件错误的I / O操作

时间:2019-03-11 22:16:48

标签: python json

代码:

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.")

上面的代码可以正常工作,直到将其添加到其中:

screenshotplaceholdertext = {"Package Screenshot URL 1":screenshoturl1}
for removescreenshotplaceholders in f:
    for screenshotplaceholder, removescreenshotplaceholder in screenshotplaceholdertext.items():
        removescreenshotplaceholders = removescreenshotplaceholders.replace(screenshotplaceholder, removescreenshotplaceholder)

f.write(removescreenshotplaceholders)

完整代码:

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.")

如果我尝试运行此代码,则会收到错误消息:ValueError:对已关闭文件的I / O操作,因此将欢迎您提供帮助。

1 个答案:

答案 0 :(得分:0)

您的问题就在这里

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 ...您已经从文件中读取了,对吗?