Files and Filenames Practice: Python Basics Exercises
Key Takeaways
This video course provides exercises to practice working with files and filenames using Python, covering topics such as reading and writing generic text files, handling comma-separated values files, and revisiting fundamental Python programming concepts. The course uses tools like idle, python, and pathlib, and covers concepts like file handling, csv, and problem-solving.
Full Transcript
welcome to another installment of python Basics exercises in this video course you'll practice reading and writing files in Python exercises provide an excellent way to strengthen your knowledge and improve your programming skills by solving our carefully selected exercises you'll practice writing code reading other people's code and communicating your thought process through these exercises you'll put the ideas you've learned in the related course or tutorial into practice and make them stick for each exercise you will follow three steps first you'll learn about the exercise I'll walk you through the relevant instructions so that you can understand the task at hand correctly then I'll give you a chance to tackle the exercise yourself practicing is the best way to reinforce your knowledge after all finally in a follow-up lesson I'll share with you my Approach showing detailed steps that lead to a working solution this way you can compare learn and elevate your own understanding note that this python Basics exercises course is broken up into three sections the first section contains a few wor up exercises that will get you to practice reading and writing generic text files in Python the exercises in the next section focus on handling comma separated values files or CSV for short which are commonly used for storing data in a tabular format you might have used those files in a spreadsheet program of your choice the last section in this quorus is a little challenge that will push you past your comfort zone letting you rise to the next level it'll give you a chance to revisit the fundamental Python Programming Concepts while providing a summary of how to work with files in python as say result you'll build something meaningful that will make it all fit together these three sections mirror the original python Basics course that this one Builds [Music] on the related course which you should watch first has a similar title minus the exercises part if you haven't watched it yet then please follow the link listed in the description below or click the link on the corresponding slide you can download the slides and other resources including sample code by expanding the supporting material drop-down which you'll find just below this video I'll be using idle or the integrated development and learning environment that comes with python to demonstrate my approach to solving the exercises so make sure that you're familiar with the tool if you've gone through other python Basics courses then you've already seen idle in action if not and you want to know more then you can check out these Associated courses that cover getting started with idle having said that if you're here outside of the the python Basics courses then feel free to use whatever tool you like to solve the upcoming coding exercises before you get started let me share a few useful tips that will help you tackle the exercises or maybe even solve actual programming problems that you might come across later at work it's always a good idea to read the instructions carefully to make sure that you understand the problem correctly try to break a bigger problem into smaller tasks that are more manageable and easier to solve take your time to think through the problem and come up with a plan before writing any code it can spare you from implementing something that you wouldn't need in the first place when writing code take small steps to help you focus on one small task at a time keep your code clean and easy to follow by giving variables descriptive and meaningful names it will help you and others understand the code more quickly occasionally you can use comments to explain difficult or surprising fragments of code try to explain why rather than the what last but not least validate each step as you go in the long run this approach can reduce the time you'll spend debugging your code when it stops working as expected all right that was the course overview I wish you good luck and I'll see you in the next lesson in this exercise you're going to save the names of Starships from the popular Star Trek franchise in a text file named Starships dotx note that the file should be saved in your home directory which is your personal folder that the operating system allocated to the corresponding user also each word in the file should be kept on a separate line you can stop the video now think about this task and C your own solution when you're ready proceed to the next lesson where you'll see my solution that you can compare with yours in this lesson I'll show you the solution to the first exercise in this section as well as my thought process behind it I already have idle open with the interactive python shell on the left and the instructions on the right to keep me reminded of what I need to do since this is going to be a file with python source code I wrap the instructions in triple quotes to define a string literal using python syntax let's go ahead and save this file as exercise1 one that will allow me to quickly run the code that I'm about to write and observe its results in the interactive shell over on the left first of all let's acknowledge the fact that there's no one correct way of solving any programming problem even though python advocates for having only one way to do it there are usually multiple different paths that ultimately lead to the same outcome so if your solution is a little bit different than mine but still works then that's perfectly fine in practice those alternative paths can involve different tradeoffs that need to be taken into account for instance it's quite typical for a faster solution to require more memory conversely one that uses less memory will often sacrifice the execution speed now the instructions that you see here don't specify how you're supposed to store these Starship names in Python you could use a list of strings for example or a single string delimited with new lines or other characters or maybe even some more sophisticated language construct available in Python like an enumeration class in this case I think that using a multi-line string literal seems the most intuitive and suitable so I will quickly grab these and and declare a variable named text just below the instructions then I'll assign a string and close in triple quotes which allow me to include multiple lines of text like so however because triple quotes preserve widespace characters this string actually includes unwanted blank lines around the Starship names you can see this when I execute the corresponding code snippet in Python's interactive shell on the left there's a new line character at the beginning as well as the end of the string probably the quickest way to suppress them is by formatting the string literal so that it starts on the same line as the variable it belongs to and so that it ends on the last Starship name however I prefer to use an explicit line continuation represented by the backslash character this might be a subjective thing but but it makes the string look a bit better to my eyes Some people prefer to rely on the so-called implicit line continuation which is yet another way of defining such multi-line strings in Python but I'm not going to cover it in this course okay now that we have a variable with Starship names it's time to save them in a text file to do that I'll import the path object from the path lip module and at the very bottom I'll Define a path pointing to a file named stars. txt notice by the way that I'm quoting the file name because I want to define a python string according to the instructions the file should be located in my home directory which I can conveniently find by calling home on the path data type let's assign this path to another variable so that I can refer to it later path seems a descriptive enough name now using this path I'll open a new file in the writing mode because we want to write to it I'll also specify the character encoding as udf8 which is always a good practice although in this case it doesn't really matter finally to make sure that python will eventually close this file reclaiming the associated resources to the operating system and flashing the internal buffers I'll wrap this line in a width statement inside that WID statement I can print our text variable but instead of printing to the screen or the standard output stream I'll specify the file to write to I can now save this module and run it to verify if there are any problems there's no output which is a good sign that means we didn't have any errors therefore we can assume the file was written successfully however to be completely sure let's try to open this file on Unix like operating systems including Mac OS and Linux you can refer to your home directory using the tilder which is this little squiggly line character here it's just a Shand notation for your home directory which you can use instead of typing out the entire path the file we're looking for is named Starships txt so let's open it now as you can see there's an extra blun line at the end of the file which is the result of calling the print function by default the print function includes a trailing new line character which you can disable by specifying the optional end parameter with an empty string as a value while this will work you can achieve the same result using even fewer characters that is by calling the right method on your file object directly passing the text variable as an argument let's save it one more time and restart the module now let's open the same file again and there's no blank line anymore apart from that each word sits on a separate line just as instructed I think that pretty much concludes this exercise see you in the next one now your task is to read the file that you created in exercise one and print each Starship name on a separate line ensuring there are no extra blun lines between them remember to specify the correct path to the file in your home directory go ahead give this exercise a try and confront Your solution with mine in the next lesson solving this exercise should take less time than before because some of the steps needed to complete it actually overlap with the ones that we've already covered in the previous exercise more specifically reading a file in Python isn't all that different from writing to it you need to first open it using the right mode so you can initially repeat the same code that you just wrote start by importing the path object and then specify the actual path to your home directory followed by the name of the file which you created in the previous exercise that is Starships txt you can assume this file exists and you can open it using the familiar WID statement but this time you want to open it for reading so you'll use the letter r instead of the letter W as the value for the mode parameter if you're a good citizen and you are right then you might as well specify the character encoding as udf8 finally you want to print each line in the file onto the screen one way to do this is by looping over the lines returned by the read lines method exposed by the file object you can then print each line to the screen even though this looks correct you should always verify your code through testing so let's save this file as a python module named exercise1 02 and let's run it okay we can see the Starship names appear correctly but they're unnecessary blun lines between them which goes against the last point in the exercise instructions at this point you might remember it's the print function that adds an extra new line character at the end of each line by default we can disable it by specifying an empty string as the value for the end parameter let's save the file and rerun it to see if that helps indeed that helps now that we verify the code works as expected we can think if there's anything we can improve about it for example the readlines method is GRE 3D which means that it loads the entire file and splits it into separate lines stuffed into a python list that could potentially allocate a lot of memory when your file is large it may be more efficient to process it line by line instead of all at once like this in such a case you can take advantage of the fact that file objects in Python are iterable themselves if you iterate over the file without calling read lines then python will keep feeding you with the next line from the file until there are no more lines or you decide to break out of the loop prematurely this should still produce the same result but use much less memory which can be especially helpful when you work with those larger files but since the Starships file is Tiny we can actually read it all at once into a python string instead of a list of lines the file object has a read method which does just that so instead of printing a line we can print the whole file again this should work as before this simplifies the code even more making me quite satisfied I actually like this solution the best what about you did you arrive at something similar this exercise is only a slight variation of the previous one so we can reuse bits of code that you might already have here you'll read the same text file again but you'll only print the Starship names that start with the uppercase letter D you don't need to worry about error checking so assume that the file already exists and contains Starship names that start with uppercase letters without further Ado let's get to it as you can see I went ahead and prepared not just the usual exercise instructions but also the solution to the previous exercise this will help speed things up as we'll build on top of it now because each name of a Starship that we want to check is kept on a separate line in the file we need to take a step back and modify the code so that it reads the file line by line I'm going to iterate over each line in the file and unconditionally print that line remembering to remove the trailing new line character just for fun I'll do it differently this time instead of telling the print function not to append the new line character I'll strip it from the right end of the line by calling the r strip method there's also a corresponding L strip method which removes the leading whes space on the other hand calling the strip method will remove both the leading and trailing whites space characters from the string let's quickly save the file and run it to test if there are no errors in the code everything seems all right but we're only interested in seeing the names that start with the uppercase letter D so that would be Discovery and defiant to filter out the other names we must introduce an if statement before printing the current line which will check whether that line starts with the uppercase letter D don't forget to indent the necessary code block under the if statement to ensure syntactical correctness this means that python will only print the line if the condition is satisfied let's check it out there we go we can see the expected output which technically ends this exercise however I'd like to extend it beyond the basics and think about some coroner cases for example I can imagine someone writing the Starship names using lower case letters or mixed case letters potentially with some extra white space around them it would be nice to account for that by cleaning the names before checking the condition you can pause the video now if you want to try implementing this yourself and then resume the video to compare Your solution with mine it'll give you a chance to revisit the knowledge of string manipulation in Python which was covered in an earlier video course in the same python basic series or the corresponding chapter in the book all right I hope that this wasn't too difficult let me now show you what I had in mind we can take the line strip all whitespace characters from both ends of the line and capitalize it so that the Starship name present on that line always starts with a capital letter finally we can assign the result of that operation to a new variable with a descriptive name such as cleancore line and we can use it for the if condition instead of the original Line This updated code ensures that we won't miss out on any Starship names regardless of how they written in the file notice that we still print the original line though you can try editing the file by hand to add new starship names or alter existing ones and then run the code again to observe changes okay let's move on to the next section of this course
Original Description
This is a preview of Python Basics Exercises: Reading and Writing Files video course. Files play a key role in computing, as they store and transfer data. You likely come across numerous files on a daily basis. This offers a few exercises to practice working with files and filenames using Python.
This is a portion of the complete course, which you can find here:
https://realpython.com/courses/python-exercises-reading-writing-files/
The rest of the course covers:
- Writing lists to CSV records
- Reading CSV files
- Dictionaries and CSV records
- A final challenge for you to test your knowledge
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: Prompt Craft
View skill →
🎓
Tutor Explanation
DeepCamp AI