Python Beginner Tutorial #9 - File Operations
Skills:
Python for Data80%
In today's episode we will learn how to operate with files. How to write into files, how to read from files and much more.
Python Documentation: https://docs.python.org/3/tutorial/inputoutput.html
Website: https://www.neuralnine.com/
Instagram: https://www.instagram.com/neuralnine
Twitter: https://twitter.com/neuralnine
GitHub: https://github.com/NeuralNine
Programming Books: https://www.neuralnine.com/books/
Outro Music From: https://www.bensound.com/
Subscribe and Like for more free content!
What You'll Learn
This video tutorial covers Python file operations, including writing to and reading from files, using Python's built-in input/output functions.
Full Transcript
what is going on guys welcome to the episode number nine of the Python tutorial series for beginners in today's video we are going to talk about file operations and we're going to take a look at how to read from files how to create files rename files and also of course had a ride in files so let's start with the code immediately because the first thing that we're going to learn today is how to open a file whenever we want to write into a file or read from a file or do anything with a file we need a so called file stream so we need to open a stream so that information can flow and to do that in Python we use the open function so what we usually do is with a finally variable for example file and then we say file it equals open and then we specify a file name for example my file dot txt and the second thing I have to specify here is I have to specify a moat and access mode how am I going to access this file am I going to access it in writing mode or in reading mode and a pinning mode and so on and we have three basic modes in Python which are reading writing and appending and there are some special X modes that we can use like reading and writing or writing bytes but for now just know that there are these basic three types or modes so W would be for writing and R would be for reading and a would be for appending and first of all we're going to read from a file but what we have here is we have a variable file that is an open file stream so in reading mode of course and what we can do now is we can use this files frame to to read from the file of course now before we get into reading and writing let's talk a little bit about how streams work now here we have our file stream opened and every stream that is open needs to be closed sooner or later so when we're not using this file any longer at the end we should always find a file that close statement file stream dot close basically we use a close method to to end the stream to no longer use it to just say ok we don't need you any longer and this is what we always have to do with writing streams especially with writing streams but also with reading streams and I'm going to explain why it's why it's more important for writing streams but for now just know when you open an a a file stream you also need to close a file stream now if you don't want to do this manually what you can do it is this oftentimes used in Python is you can use a with statement and you use a with statement whenever you have to work with streams so what you could do is you could say with open and then open the file dot txt this time it's file and not my file in reading mode and you can say as f so in this case what you're doing here is you're opening a stream as f with a width statement and the benefit that you get from this or the reason why you do this is because you don't have to close the stream because right now here I can put all of my code all of my code or a past statement whatever and everything that's indented in this with statement happens with the stream so everything that has to be done in this stream or with this stream happens in Dennett into the with statement and after the width statement we don't need the stream any longer and we close it now of course if you need to stream over and over again this is not the best method here but if you just need to use it once for reading text from a file or writing text into a file and then you want to close it again you can use a with statement because you don't need to manually close the file so let's take a look at how to read a file now first of all let's create a file on my desktop here call it file dot TX file dot txt ok now I open it file and let's put some text in here for example hello world and just save it and now what I want to do is I want to read this file into my code I want to get the input or the content of the file I want to get this as a string into my code now I will use the with statement here but I'm also going to show you how to do this without a with statement so let's just say with open file txt in reading mode SF and now I'm going to say our content equals F dot read and then we're going to print the content now when you see we get a hello world because what is what it does is it says open this file stream s F so if you want to access the file stream you just have to access F and then just save the content save what you can read from this file we use a read method here to just get the content of the file and we then want to save this content that this method returns into a variable and then we print this variable this is what we're doing and of course it works another way to do this without a with statement is to just say file equals open and then file dot txt in reading mode and then of course I would have to say content equals file dot read and I should also close the file because otherwise the stream stays open and as you can see it works now writing into files works almost the same way so instead of opening in reading mode of course we just open in writing mode and instead of using the read method here I use the write method here so I save file dot right um hello YouTube for example then I close the stream I don't have to print anything here and when I run it you will see that nothing happens but when I opened the file right now you'll see how are you - let me just scale this down a little bit you see how our YouTube because I I have overwritten the file by just writing it and now the content of the file is how our YouTube and of course this can also be done in a with statement here by just saying with open file dot txt in writing mode s F and then I just say after right hello YouTube so this would have the same effect we can test this if you want but actually I'm not going to delete this because I want to show you something so I'm just going to comment it out here and as you can see or s you will be able to see the content is still hello YouTube now why is this closed method especially important when it comes to writing this is the question that we need to cover here the close method is not just for closing the stream but what it also does is it flushes the content because if we just write into the file or use the write method and don't close the stream let's say we delete the content of the file so now it's empty and when I now run the script here you'll see that nothing happens and in the file we don't have any content because when we write something it's not in the file yet we need to use flush or closed as a method so we need to use the flush method to flush everything out of the stream into the file or we can use a closed method because the close method also flushes so basically the close method calls the flush method if you want or it flushes the stream so it doesn't matter which one you call the difference of course is when you flush the stream the stream is still open so you can use it when you close it it's close and you cannot use it now of course when you write into a file that does not exist it still works because when you use writing and the file does not exist it just creates the file but if you try to read a file that does not exist so basically content equals file dot read when you try to do this and the file is not here you will get a file not found error so this would be something that we would have to take care of when we deal with streams this is why I mentioned in the exceptions episode that when we use streams we oftentimes do try and here we put some code some stream code that we want to try then we catch some exceptions and what we then do in the end is oftentimes just use a finally statement to then close the stream so this is what I mean by which is what I meant by using exception handling with with streams especially now what you can also do is not only write into files I also mentioned that you can append onto files so let's say we already have a file here file dot txt and I have some content already in here content maybe I don't want to write into this file and override it I want to just append some text onto it so what I do then is I call or I use the appending mode and then I save file dot right I think it's right I don't think that we need to use an append method but maybe I'm going to be proven wrong let's see filed out right hello world found out flush you think this should work actually let's see yeah as you can see we just append the text we're still using the same method the writing methods the right method but since we're calling in a pending mode and not in writing mode we're just adding the text instead of overriding it now I can also try to append when the file does not exist and it will still work because if there is nothing appending also creates a new file so now let's get into some other file operations that we can do because we can use file streams to write into files to change the information and files to append onto files read from files but how do we rename files or remove files or make new directories or change the directory and so on these functionalities are not offered by file streams but we can use the so called OS module in Python so in this episode we're not only learning how to deal with files we're also learning how to import a module so what we're doing here is we can say import OS and then we can call all the u.s. methods for example OS dot rename or OS dot remove and so on or what we can also do if we don't want to do this that way we can say from OS import star which means basically everything so I can say from OS import and if I only want to import two methods for example I can say from a West import and rename but for now we're going to import everything so that we're not too confused OS is just a module that has functions and classes and different things in it and to use these I don't know functions you can just import the whole OS module so in this case we important everything and what we can now do is for example just say m'kay directory um test for example and when I run this you will see that it created a directory on my desktop with the name test because this is what this function does it makes a directory make tyreq Tory and then we can also go and navigate into that directory so I can say change directory test and then I'm in this directory now of course the problem is that now the directory already exists so actually when I call change directory I am now in the directory so when I create a new file will no longer be created on the desktop but in this directory so we can check this directory I can just make another directory new dear and delete this and you'll see that it creates a directory in a directory so this is how you can work with various different or how you can handle files and directories but you can also just remove files or rename files so let's say we have a file dot txt and what we can do is we can just say rename file dot txt and now it's called my file dot txt for example cannot find oh of course we change the directory so it does not work because it looks for a file in here so we're going to delete all this code and now it should work as you can see it's called my file dot txt because it changed just a name from five txt to my father your txt and what can I do is of course we can also just remove the file so basically deleting it by saying remove my file dot txt and as you can see it's gone so that's basically file handling in Python we learned how to read from files how to append on to files how to write into files how to overwrite files and also how to remove files rename files make directories navigate through directories and so on so that's basically what we need to know for now we're going to need with statements and file streams oftentimes in the future so make sure you learned you really understood what was taught today or what we talked about today because it's very important for future episodes and yeah so thanks for watching hit the like button if you like this video feel free to ask questions and give feedback in the comment section down below and also subscribe to this channel if you want to see more and thank you very much for watching see you in the next episode and stay tuned bye [Music] you
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeuralNine · NeuralNine · 10 of 60
1
2
3
4
5
6
7
8
9
▶
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
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
Python Beginner Tutorial #5 - Loops
NeuralNine
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
Python Beginner Tutorial #7 - Functions
NeuralNine
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
Python Beginner Tutorial #9 - File Operations
NeuralNine
Python Beginner Tutorial #10 - String Functions
NeuralNine
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
Python Intermediate Tutorial #6 - Queues
NeuralNine
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
Python Intermediate Tutorial #9 - Recursion
NeuralNine
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
Python Intermediate Tutorial #11 - Logging
NeuralNine
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
Python Machine Learning #4 - Support Vector Machines
NeuralNine
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
Making Text Images Readable Again with Python and OpenCV
NeuralNine
Neural Networks Simply Explained (Theory)
NeuralNine
Motion Filtering with OpenCV in Python
NeuralNine
Top 5 Programming Languages To Learn in 2020
NeuralNine
Simple TCP Chat Room in Python
NeuralNine
Image Classification with Neural Networks in Python
NeuralNine
Edge Detection with OpenCV in Python
NeuralNine
S&P 500 Web Scraping with Python
NeuralNine
Simple Sentiment Text Analysis in Python
NeuralNine
Introduction - Algorithms & Data Structures #1
NeuralNine
More on: Python for Data
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
7 Best AI Tools for Research, Coding, and Development in 2026
Medium · Data Science
7 Best AI Tools for Research, Coding, and Development in 2026
Medium · Programming
How to Write a Project Status Report With AI in 15 Minutes
Medium · AI
7 AI Tools That Can Save You Hours Every Week
Medium · AI
🎓
Tutor Explanation
DeepCamp AI