DEV Community

Discussion on: Solving the Problem Sets of CS50's Introduction to Programming with Python — One at a Time: Problem Set 6

Collapse
 
rivea0 profile image
Eda

Hi, that's a great idea for a solution without csv methods! The csv module actually makes the job easier and the code more readable, though.
Using DictWriter is easy, after you open the file, you just create a "writer" object and write its header field names such as:

writer = csv.DictWriter(csvfile, fieldnames=['first', 'last', 'house'])
writer.writeheader()
Enter fullscreen mode Exit fullscreen mode

Reading the "before" file is also easy, after opening it, you create a "reader" object this time, and can read each row with a loop. For example, splitting the names might look like this:

reader = csv.DictReader(before)
for row in reader:
    last_name, first_name = row['name'].split(',')
Enter fullscreen mode Exit fullscreen mode

Then, the writerow() method can be used for the writer object, passing a dictionary using the field names as keys.

One of the beautiful things in programming is that actually there are many ways for a solution, and elegance is mostly a matter of opinion. Thanks for sharing a different perspective.
And, thanks for an article idea, maybe I do a write-up some day on some basic csv methods :)

Collapse
 
aristhera profile image
Gebhard

Cool, do that.
Matter of fact I used the writer-object for writing headers just like you.
writerow() I used like:

`for i in range(len(liste)//3):
      writer.writerow({'first': liste[i*3], etc. .....})`
Enter fullscreen mode Exit fullscreen mode

and the main difference is in handling the 'before'-part. I just created the list, no reader = csv.DictReader(before)
But many roads lead to Rome and I'd love to read your piece on csv methods