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

Veröffentlicht am: 22 April 2025
auf dem Kanal: 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... .


Auf dieser Seite können Sie das Online-Video Python for non-programmers, lesson 11: Writing to files mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Python and Pandas with Reuven Lerner 22 April 2025 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 199 Mal angesehen und es wurde von 12 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!