Need help saving Data in csv file

Hi guys when I run this code:

# Open prefix, keyword, suffix and extension from files
with open("keyword.txt") as f:
   keywords = f.read().splitlines()
# csv file
with open("results.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["domain", "similar domain", "price", "year"])

# Filter similar sold domains by sale price and year

for domain in keywords:
   # Call appraisl API
   appraisal_res = requests.get(appraisal.format(domain), headers=headers).json()
   # Do not abuse the API
   time.sleep(2)
   comparable_sales = appraisal_res["comparable_sales"]  
   for sale in comparable_sales:
      if comparable_sales:
         similar_domain = "{:30} : {:10} : {:10}".format(sale["domain"], sale["price"], sale["year"])
         writer.writerow([domain, similar_domain])
         print(f"{domain}, {similar_domain}")

it shows me ValueError: I/O operation on closed file in this line:

writer.writerow([domain, similar_domain])

what’s wrong?

The for domain in keywords: loop is outside of the with open("results.csv", "w", newline="") as file: file handler, which will close the "results.csv" file before the code logic reaches it.

Try:

# csv file
with open("results.csv", "w", newline="") as file:
   writer = csv.writer(file)
   writer.writerow(["domain", "similar domain", "price", "year"])

   # Filter similar sold domains by sale price and year

   for domain in keywords:
      # Call appraisl API
      appraisal_res = requests.get(appraisal.format(domain), headers=headers).json()
      # Do not abuse the API
      time.sleep(2)
      comparable_sales = appraisal_res["comparable_sales"]  
      for sale in comparable_sales:
         if comparable_sales:
            similar_domain = "{:30} : {:10} : {:10}".format(sale["domain"], sale["price"], sale["year"])
            writer.writerow([domain, similar_domain])
            print(f"{domain}, {similar_domain}")

Thanks, problem solved

1 Like