Python Programming Tutorial #13 - How to Read a Text File
Skills:
Python for Data80%
Key Takeaways
This video tutorial demonstrates how to read a text file using Python, covering the importance of file modes and directory placement for successful file reading.
Full Transcript
hey guys welcome back this is the 13th video in my Python Programming series and today we're going to be talking about reading from a file so specifically a text file and we're going to be using something called file.io in Python so the first thing we need to do before we can read from a file is we need to create a file so I'm just simply going to go and find the directory where my python tutorials are so oops not here they are right here in the tutorials folder um and now you see I've got all my python uh scripts right here and all I'm going to do is I'm going to right click and I'm going to click new and then I'm going to find text document like that now I can name it whatever I like I'm just going to name it file for right now file. text now you may want to populate the uh text document so put some words in here so I'm just going to put a bunch of different words hello Tim python Learning Easy just some random random words in my text file I'm going to save that um and now we can go to reading in the text file so it is important that when you make the text file you do have to save it in the same directory as your python script so if I were to put the text file here on my desktop and I have my python script in the tutorials folder here it's not going to be able to find the file properly um you would have to do something which is a path joining which I'm not going to talk about in this video but maybe in a later so make sure that you save your file in the same directory uh and same folder as where your script is okay so now that we've done that we're going to read from the file so the first thing we need to do is we need to create a variable so we're going to name this file you can name it whatever you'd like and you're going to set it equal to the keyword open and then inside of open all you're going to do is you're going to type the name of your file so file. text a comma and then the mode you want to open your file in so so in this case we want to read it so we're simply going to put a lowercase R inside of the quotations just like that and now that's pretty simple that's all you have to do in Python to open up the file and to prepare to read it now make sure you do put R in here if you put nothing or you put a W for example which would be write mode it's actually going to clear the whole file which you don't want to happen you want to leave the contents of the file in there right so we need to open it in read mode with this R that's very important um now what we're going to do is we're simply going to read all of the things from the file so we've opened the file now we need to read it so in order to read the file uh we have to type a few things so we can do it in multiple different ways the first way I'm going to show you is this so I'm going to make another variable I'm going to call it f and this one we're going to make it equal to file. read lines like this okay and then we can simply print out F just to show you what's going to happen you see we get all of the words that are in the file now there's an interesting thing here you may notice that there's a back sln attached to all of the words except for the last one that's because I'm going to open up the text file again and show you um you notice here I didn't actually type back sln but every time we click enter like this it actually creates something called an escape character which is that back sln so if we want to read in the file we're going to have to remove that um character afterwards right so it's just something to keep in mind that if you have things on different lines each of the end of the lines is going to have a back sln on that line that you don't actually see here in the text document but python will read that in okay so we don't need to save that um yeah so let's move into the second way to read it properly now so we have f equals file. read lines now we want to remove all of these back slashes uh get rid of these ends from our lines so so there's a way we have to do that and it's by using a for Loop so we're going to do a for Loop just going to say for line in F because now F has read all of our lines so we're going to do what's called iterating by item if you remember from my other videos so each line so every item in this F list here that just created by file. read lines we're going to remove that character and we're going to create a new list so let's make a new list we'll call it new list just make it a blank list like this new list and then here we're going to say um what is it new list do append and if you remember what aend does that simply means add to the end um of this new list and then we're going to add the line and we're going to use the slice operator to remove that back sln so we're going to Simply do the colon and then -1 now what this does is we it will take all of line except for the last character so negative one um I didn't talk about this in the other video but negative 1 pretty much just goes to the last character but does not include the last character when you do negative one like this so just just follow along for now you don't have to completely understand it but just put that negative 1 and now if I print out new list we'll see what we get new list F5 and you see we get rid of all of the back slash ends now we have one issue here um down here on ease uh it should say easy but we've actually removed the last back sln from that string so if we don't want to do that now we need to actually add an if statement into our for Loop so inside of the for loop we're going to type if and then we'll say line and we'll put a negative 1 again to represent the last character in that line equals equals back sln and then we'll simply tab this in because remember everything in Python needs to be indented proper properly for it to be read um and now we'll try this and we'll see if this works and there we go so we get hello Tim Python and learning but now we forgotten one thing we haven't actually included easy so now we need to do an else statement so we have else and then we'll do new list. append and we'll simply append the line just like that and now we can print it out and we will see what happens and we get hello Tim python learning and easy now there is an easier way to do this I just wanted to show this example because you may want to do something where you're checking through all of the lines and you want to see if the last character or maybe the first character is equal to a certain item and depending on what that string is or depending on what it is you may want to add it to a new list you may want to do something to it so I just want to show you a way that we can do that pretty much this is iterating through every line in the file so file here so F creates a list of every line and then we go through through every line of it and we see we say if the end of it has this back sln then we're going to remove the back sln um otherwise we'll just add that line into our list right okay so now the easier way that we can do this is actually with something that's called The Strip string method so in my other video I talked about this strip method that removes the spaces but what we can actually do with this uh is we can remove what do you call it sorry we can remove the back sln with the strip method as well so all we have to do here now it's a lot simpler you do new list. append and then inside of here we're simply going to type line. strip and now this will automatically remove those back SL ends and we'll see if this works there we go so we get everything and you can see it's a lot simpler and we don't even have to do the if statement um for the easy like that so that pretty much is how you read a file in using python there are some other ways to do this but this is the most basic and easiest way to understand we've also talked about how to remove that it's called an escape character at the end of the string that back sln and in the next video we're going to talk about writing to a file I hope you learned something if you did please like And subscribe and I will see you again in another video
Original Description
This is the 13th video in my python programming series. Today I talk about how to read from a text file using python.
Note: Make sure your file in in the directory as your python script or else this will not work! Also make sure you use the 'r' file mode.
Text-Based Tutorial: https://techwithtim.net/tutorials/python-programming/beginner-python-tutorials/file-io-reading-files/
Please LIKE and SUBSCRIBE for more content.
Video Tags:
python,python tutorial,python language,python full course,python course,learn python,learn python programming,python tutorial for beginners,python tutorial 2018,python programming tutorial,python programming language,software development,programming tutorial,tech with tim, reading a text file
Playlist
Uploads from Tech With Tim · Tech With Tim · 15 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
▶
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* Path Finding Algorithm(Visualization)
Tech With Tim
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
Python Programming Tutorial #3 - Conditions
Tech With Tim
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
Python Programming Tutorial #6 - For Loops
Tech With Tim
Python Programming Tutorial #7 - While Loops
Tech With Tim
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
Python Programming Tutorial #10 - String Methods
Tech With Tim
How to Overclock a NVIDIA GPU
Tech With Tim
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
Python Programming Tutorial #12 - Functions
Tech With Tim
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
Cool VBS Script to Prank Your Friends!
Tech With Tim
How to Overclock an AMD GPU
Tech With Tim
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
Recursion and Memoization Tutorial Python
Tech With Tim
Ethereum Mining Rig - Hardware Guide
Tech With Tim
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
How to Install Pygame (Windows 8/10)
Tech With Tim
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
Linear Search Algorithm - Python Example and Code
Tech With Tim
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Tech With Tim
Pygame Tutorial #5 - Projectiles
Tech With Tim
Pygame Game - Mini Golf
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
Pygame Tutorial #6 - Enemies
Tech With Tim
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
How to Create A Message Box in Python - Tkinter
Tech With Tim
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim
More on: Python for Data
View skill →
🎓
Tutor Explanation
DeepCamp AI