BLACK FRIDAY EXTRA SAVINGS EVENT - EXTENDED
START FREE

How to save changes made to a file

Data cleaning course: https://app.dataquest.io/m/351/cleaning-and-preparing-data-in-python/5/string-capitalization

Code used:

from csv import reader

OpenFile = open('Animal Names.csv')
ReadFile = reader(OpenFile)
AnimalNames = list(ReadFile)

for row in AnimalNames:
    dogs = row[0]
    cats = row[1]

    dogs = dogs.title()
    cats = cats.title()

    row[0] = dogs
    row[1] = cats

print(AnimalNames)

From the Data cleaning course listed above I tried the same coding technique on a personally owned set of data and it worked just fine(which is great thanks DataQuest). My issue came around when I closed out the code and opened the excel back up none of the changes were saved. How do I go about actually saving those changes made back to the document? Thank you!!

Hi @burnsdillion

Go through the below post.

You can also download your project on going to the file button on Juypter Notebook and then Download as in any format.

I hope this helps :slight_smile: .

1 Like

Hey @Prem thanks for replying!!

That is a great resource but I believe it still doesn’t answer my question.

I was more directed towards saving the results of the code using code. So all of the data cleaning and such I do on the specific data I want to save those changes back into the file that was opened originally so that I can open the excel and see the results of my code.

Thank you!!

To do this, you’ll need to do two things:

  • Open the file in write mode
  • Use csv.writer()

Here’s some basic code on how to do this. I would strongly suggest not writing to the original filename, because it will overwrite the data and if you make a small error your original data is gone.

from csv import writer

t = [['a', 1],
     ['b', 2],
     ['c', 3]]

# specify write mode with the 'w' argument
f = open('test.csv', 'w')

# create a writer object
w = writer(f)
# use the writer object to write to the file
w.writerows(t)

As you continue to go through the dataquest material, you’ll learn to use pandas - opening and saving to files is a lot easier with pandas, so you’ll end up using that technique most of the time (although it’s worthwhile knowing the “manual way” as well!)

3 Likes

Thank you! I will store this in my resources :slight_smile: