首页 > 解决方案 > 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.

标签: pythonjson

解决方案


你的问题就在这里:

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


推荐阅读