FAQ: Learn Python: Files - Writing a CSV File

This community-built FAQ covers the “Writing a CSV File” exercise from the lesson “Learn Python: Files”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Python 3

FAQs on the exercise Writing a CSV File

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

8 posts were split to a new topic: How does .writeheader() know the fields to use?

A post was split to a new topic: Why doesn’t this work?

Undefined variable: ‘fieldnames’

That is the error I get in VSC on line 8. space 56.

import csv

access_log = [{'time': '08:39:37', 'limit': 844404, 'address': '1.227.124.181'}, {'time': '13:13:35', 'limit': 543871, 'address': '198.51.139.193'}, {'time': '19:40:45', 'limit': 3021, 'address': '172.1.254.208'}, {'time': '18:57:16', 'limit': 67031769, 'address': '172.58.247.219'}, {'time': '21:17:13', 'limit': 9083, 'address': '124.144.20.113'}, {
    'time': '23:34:17', 'limit': 65913, 'address': '203.236.149.220'}, {'time': '13:58:05', 'limit': 1541474, 'address': '192.52.206.76'}, {'time': '10:52:00', 'limit': 11465607, 'address': '104.47.149.93'}, {'time': '14:56:12', 'limit': 109, 'address': '192.31.185.7'}, {'time': '18:56:35', 'limit': 6207, 'address': '2.228.164.197'}]
fields = ['time', 'address', 'limit']

with open("10 - Writing a CSV File\logger.csv", 'w') as logger_csv:
    log_writer = csv.DictWriter(logger_csv, fieldnames=fields)
    log_writer.writeheader()
    for _ in access_log:
        log_writer.writerow(_)

Why am I getting this error in VSC(this code works on this site)?
Using Python 3.7.5 64bit on Windows.

1 Like

I see no error

Not sure why, but when I close the folder and then the program and reloaded it all the error went away. :man_shrugging:

You have a warning. If you read the warning, you’ll find it makes no sense.
You could consider what the source of that warning is. Likely a linter. What is that linter looking at? An old version of your file?
An error would prevent you from running the code.

It had to be the linter. Just weird at that moment that the code worked with what I thought was an error. Makes sense now that it worked without error because it was a warning.

Aside from that,

The variable name _ is something you’d use to say “I don’t care about this”
but you’re using it. a bit odd!

If you run a formatter on that code you’d end up with something like:

import csv

access_log = [
    {"time": "08:39:37", "limit": 844404, "address": "1.227.124.181"},
    {"time": "13:13:35", "limit": 543871, "address": "198.51.139.193"},
    {"time": "19:40:45", "limit": 3021, "address": "172.1.254.208"},
    {"time": "18:57:16", "limit": 67031769, "address": "172.58.247.219"},
    {"time": "21:17:13", "limit": 9083, "address": "124.144.20.113"},
    {"time": "23:34:17", "limit": 65913, "address": "203.236.149.220"},
    {"time": "13:58:05", "limit": 1541474, "address": "192.52.206.76"},
    {"time": "10:52:00", "limit": 11465607, "address": "104.47.149.93"},
    {"time": "14:56:12", "limit": 109, "address": "192.31.185.7"},
    {"time": "18:56:35", "limit": 6207, "address": "2.228.164.197"},
]
fields = ["time", "address", "limit"]

with open("10 - Writing a CSV File logger.csv", "w") as logger_csv:
    log_writer = csv.DictWriter(logger_csv, fieldnames=fields)
    log_writer.writeheader()
    for _ in access_log:
        log_writer.writerow(_)

…which is a fair bit nicer.

DictWriter has a writerows, don’t need the loop

with open("10 - Writing a CSV File logger.csv", "w") as logger_csv:
    log_writer = csv.DictWriter(logger_csv, fieldnames=fields)
    log_writer.writeheader()
    log_writer.writerows(access_log)

(also, you somehow have \l in there (and your linter should catch it))

1 Like

Why in this exercise do we not have to define the field names?
I defined the field names as in the example, but the system rejected the code. When I commented out the list of fields, the code was accepted.

import csv

with open(‘logger.csv’, ‘w’) as logger_csv:
#fields = [‘time’, ‘limit’, ‘address’]. <-----------This list was created in the example, but throws an error ##when used in the exercise.
log_writer = csv.DictWriter(logger_csv, fieldnames=fields)

log_writer.writeheader()
for item in access_log:
log_writer.writerow(item)

Also if I wanted to print to see the result how do I do that?
I did print(dict(logger_csv))
print(item(logger_csv)) but they don’t work

4 Likes

When I use the .writerow() command in my program with my csv file, when I open it as a workbook with Excel it has skipped rows as it writes. Why is this? Any thoughts on my code below.

import csv

data_stuff = [{'name':'Mike', 'age':'35', 'sex':'M'}, {'name':'Jenny', 'age':'34','sex':'F'}, {'name':'Elijah', 'age':'4', 'sex':'M'}]

with open('book1.csv', 'w') as book:
    fields = ['name', 'age', 'sex']
    new_book = csv.DictWriter(book, fieldnames=fields)

    new_book.writeheader()
    for items in data_stuff:
        new_book.writerow(items)

image

Ah, my problem was that I was trying to rename the fields in the fields variable. Once I named the fields exactly as in the list of dicts, it worked:

import csv

with open('logger.csv', 'w') as logger_csv:
  fields = ['time', 'limit', 'address']
  log_writer = csv.DictWriter(logger_csv, fieldnames=fields)

  log_writer.writeheader()
  for item in access_log:
    log_writer.writerow(item)

Why in this line is the keyword specified?

log_writer = csv.DictWriter(logger_csv, fieldnames=fields)

I tried it without:

log_writer = csv.DictWriter(logger_csv, fields)

It works fine. The output files are identical. Why bother?

1 Like

Why did we use specific fields list in the example given in this lesson but when we did the exercise we did not need to? How does the program know which fields to take as field names?

import csv

with open(‘output.csv’, ‘w’) as output_csv:
fields = [‘name’, ‘userid’, ‘is_admin’]
output_writer = csv.DictWriter(output_csv, fieldnames=fields)

output_writer.writeheader()
for item in big_list:
output_writer.writerow(item)

compared to:

import csv

with open(‘logger.csv’,‘w’) as logger_csv:

log_writer = csv.DictWriter(logger_csv, fieldnames = fields)

log_writer.writeheader()

for item in access_log:

log_writer.writerow(item)

How do we append to an existing csv file using “a” mode? Do we simply loop over the list and “writerow()” for each item? Do we have to account for the “Header” like we did for writing a new file (i.e. using the .writeheader() function)?

When I did this exercise, the list of field names were provided, but this is not your case?

fields = ['time', 'address', 'limit']

Hello there, the output for this lesson, I got:

31
32
29
34
30
32
32
33
27
29

Code:

import csv
with open("logger.csv",'w') as logger_csv:
  log_writer=csv.DictWriter(logger_csv, fieldnames=fields)
  log_writer.writeheader()
  for n in access_log:
    print(log_writer.writerow(n))
    

Why did I get this output instead of the file logger.csv elements? Or what should be the output?

In my solution to the problem in the lesson, if I use the line in the lesson itself “open(‘books.csv’, newline=’’)”, the
system responds

“Since we want to open “books.csv” in read mode we don’t need to pass additional arguments to open()”.

When I take out the newline part and just use “open(‘books.csv’)”, the systems accepts it as valid and the error is not
returned.

Why is it flagging as an error the data that was explicitly in the lesson ?

Welcome back to the forums!

Can you post the link to the exercise you mentioned? The exercise associated with this forum topic doesn’t seem to match.

Presumably, what went wrong is that you provided a newline argument when the exercise didn’t ask for one, rendering your answer incorrect.

Also, for reference (in case you want to learn more about the parameters for open():
https://docs.python.org/3/library/functions.html#open