Python for non-programmers, lesson 11: Writing to files

Publié le: 22 avril 2025
sur la chaîne: Python and Pandas with Reuven Lerner
199
12

Learn how to write data to files in Python — and start saving your programs' output for future use.

Last time, we looked at how we can read from files, taking stored text and turning it into data structures in memory. In this lesson, we look at how we can write to files, taking our in-memory data structures and writing them to disk.

To download the Jupyter notebook I created when teaching this lesson, sign up (for free) at https://PythonForNonProgrammers.com .

-----

Homework exercises for this lesson:

1. Write a program that asks the user to enter sentences, one at a time. Stop asking when the user enters an empty string. Write each word that the user entered on a separate line of a file, followed by a space and the number of vowels that the user wrote.

So if the user enters ‘this is a test’ and ‘only kidding’, then the file should look like:

this 1
 is 1
 a 1
 test 1
 only 1
 kidding 2

2. Let’s pretend that we’re creating a sales report for our company. Repeatedly ask the user to enter a product name and a number of units sold. (The products and units don’t matter, but should be separated by whitespace.) When the user enters a blank line, stop asking. Write this into a CSV-like file (i.e., with a comma separating the two pieces of information). If the file has a csv extension, see if you can open it with Excel on your computer.

The files we used for the reading exercises and examples are all at https://files.lerner.co.il/exercise-f... .


Sur cette page du site, vous pouvez voir la vidéo en ligne Python for non-programmers, lesson 11: Writing to files durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Python and Pandas with Reuven Lerner 22 avril 2025, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 199 fois et il a aimé 12 téléspectateurs. Bon visionnage!