Python Tutorial - 13. Reading/Writing Files
Skills:
Python for Data80%
Key Takeaways
Reading and writing files in Python using open function and file modes
Full Transcript
hello everyone welcome to another session of code Basics coding tutorial today's topic is reading and writing to a file and here is the list of items we are covering in this video okay let's begin with creating a new file and writing some content to it as you can see here I have C data directory which is completely empty I do not have any file what I want to do is create a new file called funny txt and write some statement into it for that you use open statement open will open a new file either for reading or writing the first parameter in this uh open function is the complete path of the file name so I'm using C column SL SL data/ funny. txt now why am I using two slashes here if I don't use two slash and just one slash then that has a special meaning and it won't work right so that's why I need to use two slashes here whenever I'm specifying the path of the file name okay so the first parameter is the file name and the second parameter is the mode in which you want to open the file I want to write the file so that's why I'm using W which means write now let's write something into it this has us this uh file handle has a function call right where I can say okay I love Python and once you done writing to it you should close it closing uh file will free up all the resources that operating system is going to allocate uh for this file all right let's run it okay so looks like it executed F fine and now if I look at my C data directory I'm seeing this file now funny. txt if I open it I will see I love python excellent okay now let me write uh some different lines so instead of python I'm saying JavaScript if I execute it again and open this then I see I love JavaScript but one thing you noticed here is it overwrote the previous content I previously had iow Python and now I have iow JavaScript what if I don't want to overwrite the file and just appen the content do it for that you need to use a different Mode called appan so just remember whenever you say w mode it will always overwrite the file so you need to say a means appen and now as you see I have I love JavaScript and I'm just going to use some different statement here and I say I love C++ and I run it see what happens so it had IO JavaScript now it appended iow C++ now this was in the same line if you want to append it in a new line then you need to use SL n character which is a new line character and you can say I love PHP when you run it um if I open it again you will notice now I have I love PHP in a new line okay now let's see how you can work on uh reading a file uh line by line all right for this we're going to uh work on a simple problem where your funny. txt so I'm going to open funny. txt erase all the content and I'm going to put this funny dialogue here okay you can take a moment and read it it's quite funny all right so what I want my Python program to do is read this file and for each of the line I want to count the number of words and towards the end it should append the word count and what I want is I want to create a new file so let me first save it okay my Python program will run on this file it will create a new file with a word count at the end of each line okay so first let me open this file in reading mode so if you want to read the file the mode that you specify is R okay and if you want to Now read the lines one by one first first let me show you how I can uh read the entire file content in one shot all right so when I say print f. read and you always do f. close let me run it cool you can see in the output that it read the whole file and it just printed the contents here so f. rate gives you the entire file content now this is not what I what I want because I want to count number of words in each line so I want to go through this file line by line for this you have to use four Loop when you say for line in F this will iterate through file one by one and every time line will have one specific line from that file okay so let me first print it just to show you that I'm not lying it is working as per what I just mentioned F do close let me run this again when I run it again again now you see every time it is reading one line if you want to count uh the number of words in this line now now what you have to do is uh say you have this file how do you count number of words words are basically separated by spaces like these okay so if you can somehow detect these spaces then you will be able to figure out number of words in Python there is a function on a string called split So when you say line do split what you're doing is you have a string and you are splitting the that string using this separator so I'm using space as a separator and when I do that it will give me list of tokens tokens is nothing but the list of words okay um let me just print those tokens here so I will say St Str tokens you notice what just happened I went through each line one by one and for every line I split it using space what that gives me is a list of words which is an array when I print it you see that this array right now all you have to do is now you have an array with list of words all you have to do do is just uh take the count and how do you take the count you use Lan command so L okay when I run it voila I get the word count now what I want to do is I want to open another file called fcor out and I will use the same path and I will say Okay I want want to name this file as funcore WC which means word count and open it in a right mode so that you can write to it okay and here you will say f. out. write so when you want when you say write it is going to write a new line into this new file now what do we want to write here we want to write the original line as well as the word count so my original line is line okay and when you want to append to a string you can use plus operator plus operator is going to just happen to that string so I will say word count and what is my word count St Str of L of tokens okay alien tokens will give you the word count and you want to convert it to a string so that you can append it to another Str and you can just remove this one and once everything is done you want to close the handle for the output file as well okay let's run it okay so looks like it finished successfully now let's look at our C data directory excellent now I see a new file called funny uncore word count.txt when I open this h i see a little problem okay so it printed word count but it was in a new line because I think we had let's see [Music] line okay we had I see so we had uh Slash n so that's why it towards the end and that's why it printed word count in the next line what we can do is we can we can print word code at the beginning of the line and for doing that just happen uh this line towards the end okay let's run it again okay it executed fine now let me open funny work count when I open it what I see is this okay so word count six so this line has six words 1 2 3 4 5 6 that's why word count is six and so on okay so that was a real fun exercise um now let's talk about file opening modes a little more uh we we already covered few mod such as read which is used for reading the file only if you open a file in read mode you cannot write to it similarly if you open a file in a right mode you cannot read you cannot read it so if you want to open a file uh both for reading and writing then you use r+ so that will open a file for reading as well as writing uh similarly if you use w+ then that will also open file for reading and writing then what's the difference between the two here the difference is if you open file like this and if let's say this file doesn't exist on your hard disk it will create the file versus in this mode it will not create the file uh if the file doesn't exist so that's a difference otherwise they both both the modes are pretty much same and the next mode that we cover was a which is append mode where you can uh appen to an existing file there are other file modes as well uh if you just Google it uh it will the P python documentation page will show you all the different modes one last thing we want to cover is a with statement here you saw that you have to explicitly open and close the file if you don't want to close the file uh explicitly cuz sometimes if you're writing a big program you may forget that and that's not good uh so for that if you want to avoid this kind of situation you use uh width statement so I will use withd statement so you'll say width open C data funny. txt for for reading mode as F when you do this it will do the same thing except that you don't have to now close the file I will say f. read okay now how do I know if file gets closed automatically with with statement you can print f. closed flag this f. closed Flags flag tells you whether the file is open or closed okay let me run it okay I'm seeing some error here oh I see I forgot one SL that's why okay so first thing what it did is f. R printed this much output which is just the file content and the second thing is here it is saying true meaning f. closed is true meaning with statement automatically close this file okay so that was all about files thanks for watching and don't forget to work on these sample exercises [Music]
Original Description
In this python tutorial, we will clarify about reading/ writing files, how to work with a file, how to open, create and close a file, use of “functions”, “modules” and “flags”.
Code used in this tutorial: https://github.com/codebasics/py/blob/master/Basics/13_read_write_file.py
Exercise: https://github.com/codebasics/py/blob/master/Basics/Exercise/13_read_write_files/read_write_file_exercise.md
Topics that are covered in this Python Video:
0:00 Overview
0:32 Open() function
1:35 write() function
1:51 close() function
2:54 append mode in a file
4:06 read from a file
5:10 read mode in a file
5:35 read() function
7:19 Split() function
11:50 File opening modes
13:23 with statement
14:16 close Flag in file
Do you want to learn technology from me? Check https://codebasics.io/ for my affordable video courses.
Next Video:
14. if __name__ == "__main__": https://www.youtube.com/watch?v=2AKJzc-cSj8&list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0&index=17
Website: https://codebasics.io/
Facebook: https://www.facebook.com/codebasicshub
Twitter: https://twitter.com/codebasicshub
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from codebasics · codebasics · 13 of 60
1
2
3
4
5
6
7
8
9
10
11
12
▶
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
Python Tutorial - 1. Install python on windows
codebasics
Python Tutorial - 2. Variables
codebasics
Python Tutorial - 3. Numbers
codebasics
Python Tutorial - 4. Strings
codebasics
Python Tutorial - 5. Lists
codebasics
Python Tutorial - 6. Install PyCharm on Windows
codebasics
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
Python Tutorial - 8. If Statement
codebasics
Python Tutorial - 9. For loop
codebasics
Python Tutorial - 10. Functions
codebasics
Python Tutorial - 11. Dictionaries and Tuples
codebasics
Python Tutorial - 12. Modules
codebasics
Python Tutorial - 13. Reading/Writing Files
codebasics
How to install Julia on Windows
codebasics
Python Tutorial - 14. Working With JSON
codebasics
Julia Tutorial - 1. Variables
codebasics
Julia Tutorial - 2. Numbers
codebasics
Python Tutorial - 15. if __name__ == "__main__"
codebasics
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
Python Tutorial - 16. Exception Handling
codebasics
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
Julia Tutorial - 4. Strings
codebasics
Python Tutorial - 17. Class and Objects
codebasics
Julia Tutorial - 5. Functions
codebasics
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
Julia Tutorial - 7. For While Loop
codebasics
Python Tutorial - 18. Inheritance
codebasics
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
Julia Tutorial - 10. Exception Handling
codebasics
Python Tutorial - 19. Multiple Inheritance
codebasics
Python Tutorial - 20. Raise Exception And Finally
codebasics
Python Tutorial - 21. Iterators
codebasics
Python Tutorial - 22. Generators
codebasics
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
Python Tutorial - 24. Sets and Frozen Sets
codebasics
Python Tutorial - 25. Command line argument processing using argparse
codebasics
Debugging Tips - What is bug and debugging?
codebasics
Debugging Tips - Conditional Breakpoint
codebasics
Debugging Tips - Watches and Call Stack
codebasics
Python Tutorial - 26. Multithreading - Introduction
codebasics
Git Tutorial 3: How To Install Git
codebasics
Git Tutorial 1: What is git / What is version control system?
codebasics
Git Tutorial 2 : What is Github? | github tutorial
codebasics
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
Git Github Tutorial 10: What is Pull Request?
codebasics
Git Tutorial 7: What is HEAD?
codebasics
Git Tutorial 9: Diff and Merge using meld
codebasics
Difference between Multiprocessing and Multithreading
codebasics
Python Tutorial - 27. Multiprocessing Introduction
codebasics
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
Git Tutorial 8 - .gitignore file
codebasics
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
Python Tutorial - 30. Multiprocessing Lock
codebasics
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
What is code?
codebasics
Python unit testing - pytest introduction
codebasics
More on: Python for Data
View skill →Related Reads
📰
📰
📰
📰
I Asked Claude to Audit My Entire Income Strategy. What It Found Was Uncomfortable.
Medium · AI
7 AI Tools Every Freelancer Should Learn in 2026 (To Work Smarter, Not Harder)
Medium · AI
How to prepare for Spain civil service TIC exam using AI in 2026
Dev.to AI
AI-Powered Sample Clearance: Building Legally-Aware Reports for Independent Producers
Dev.to AI
Chapters (12)
Overview
0:32
Open() function
1:35
write() function
1:51
close() function
2:54
append mode in a file
4:06
read from a file
5:10
read mode in a file
5:35
read() function
7:19
Split() function
11:50
File opening modes
13:23
with statement
14:16
close Flag in file
🎓
Tutor Explanation
DeepCamp AI