Save a list of dictionaries as a CSV file. Args: data: a list of dictionaries filename: the name of the CSV file to save
(data, filename, log=True)
| 231 | return [x for x in data if isinstance(x, dict)] |
| 232 | |
| 233 | def write_csv(data, filename, log=True): |
| 234 | """ |
| 235 | Save a list of dictionaries as a CSV file. |
| 236 | |
| 237 | Args: |
| 238 | data: a list of dictionaries |
| 239 | filename: the name of the CSV file to save |
| 240 | """ |
| 241 | import csv |
| 242 | |
| 243 | data = clean_data(data) |
| 244 | data = convert_nested_to_json(data) |
| 245 | |
| 246 | filename_new = append_output_if_needed(filename) |
| 247 | |
| 248 | |
| 249 | if not filename_new.endswith(".csv"): |
| 250 | filename_new = filename_new + ".csv" |
| 251 | |
| 252 | try: |
| 253 | with open(filename_new, "w", newline="", encoding="utf-8") as csvfile: |
| 254 | fieldnames = get_fields(data) |
| 255 | writer = csv.DictWriter(csvfile, fieldnames=fieldnames) |
| 256 | writer.writeheader() # write the header row |
| 257 | for i in data: |
| 258 | writer.writerow(i) # write each row of data |
| 259 | if log: |
| 260 | print(f"View written CSV file at {filename_new}") |
| 261 | |
| 262 | except PermissionError: |
| 263 | prompt( |
| 264 | f"{filename_new} is currently open in another application (e.g., Excel). Please close the the Application and press 'Enter' to save." |
| 265 | ) |
| 266 | return write_csv(data, filename, log) |
| 267 | return filename_new |
| 268 | |
| 269 | def save_image(url, filename=None): |
| 270 | import requests |
no test coverage detected