Python Tutorial - 13. Reading/Writing Files

codebasics · Beginner ·🛠️ AI Tools & Apps ·10y ago

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 Python Tutorial - 1. Install python on windows
Python Tutorial - 1. Install python on windows
codebasics
2 Python Tutorial - 2. Variables
Python Tutorial - 2. Variables
codebasics
3 Python Tutorial - 3. Numbers
Python Tutorial - 3. Numbers
codebasics
4 Python Tutorial - 4. Strings
Python Tutorial - 4. Strings
codebasics
5 Python Tutorial - 5. Lists
Python Tutorial - 5. Lists
codebasics
6 Python Tutorial - 6. Install PyCharm on Windows
Python Tutorial - 6. Install PyCharm on Windows
codebasics
7 PyCharm Tutorial - 7. Debug python code using PyCharm
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
8 Python Tutorial -  8. If Statement
Python Tutorial - 8. If Statement
codebasics
9 Python Tutorial - 9. For loop
Python Tutorial - 9. For loop
codebasics
10 Python Tutorial -  10. Functions
Python Tutorial - 10. Functions
codebasics
11 Python Tutorial - 11. Dictionaries and Tuples
Python Tutorial - 11. Dictionaries and Tuples
codebasics
12 Python Tutorial - 12. Modules
Python Tutorial - 12. Modules
codebasics
Python Tutorial - 13. Reading/Writing Files
Python Tutorial - 13. Reading/Writing Files
codebasics
14 How to install Julia on Windows
How to install Julia on Windows
codebasics
15 Python Tutorial - 14. Working With JSON
Python Tutorial - 14. Working With JSON
codebasics
16 Julia Tutorial - 1. Variables
Julia Tutorial - 1. Variables
codebasics
17 Julia Tutorial - 2. Numbers
Julia Tutorial - 2. Numbers
codebasics
18 Python Tutorial - 15. if __name__ == "__main__"
Python Tutorial - 15. if __name__ == "__main__"
codebasics
19 Julia Tutorial - Why Should I Learn Julia Programming Language
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
20 Python Tutorial  - 16. Exception Handling
Python Tutorial - 16. Exception Handling
codebasics
21 Julia Tutorial - 3. Complex and Rational Numbers
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
22 Julia Tutorial - 4. Strings
Julia Tutorial - 4. Strings
codebasics
23 Python Tutorial -  17. Class and Objects
Python Tutorial - 17. Class and Objects
codebasics
24 Julia Tutorial - 5. Functions
Julia Tutorial - 5. Functions
codebasics
25 Julia Tutorial - 6. If Statement and Ternary Operator
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
26 Julia Tutorial - 7. For While Loop
Julia Tutorial - 7. For While Loop
codebasics
27 Python Tutorial  - 18. Inheritance
Python Tutorial - 18. Inheritance
codebasics
28 Julia Tutorial - 8. begin and (;) Compound Expressions
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
29 Python Tutorial - 12.1 - Install Python Module (using pip)
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
30 Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
31 Julia Tutorial - 10. Exception Handling
Julia Tutorial - 10. Exception Handling
codebasics
32 Python Tutorial  - 19. Multiple Inheritance
Python Tutorial - 19. Multiple Inheritance
codebasics
33 Python Tutorial - 20. Raise Exception And Finally
Python Tutorial - 20. Raise Exception And Finally
codebasics
34 Python Tutorial - 21. Iterators
Python Tutorial - 21. Iterators
codebasics
35 Python Tutorial - 22. Generators
Python Tutorial - 22. Generators
codebasics
36 Python Tutorial - 23. List Set Dict Comprehensions
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
37 Python Tutorial - 24. Sets and Frozen Sets
Python Tutorial - 24. Sets and Frozen Sets
codebasics
38 Python Tutorial - 25. Command line argument processing using argparse
Python Tutorial - 25. Command line argument processing using argparse
codebasics
39 Debugging Tips - What is bug and debugging?
Debugging Tips - What is bug and debugging?
codebasics
40 Debugging Tips - Conditional Breakpoint
Debugging Tips - Conditional Breakpoint
codebasics
41 Debugging Tips - Watches and Call Stack
Debugging Tips - Watches and Call Stack
codebasics
42 Python Tutorial - 26. Multithreading - Introduction
Python Tutorial - 26. Multithreading - Introduction
codebasics
43 Git Tutorial 3:  How To Install Git
Git Tutorial 3: How To Install Git
codebasics
44 Git Tutorial 1: What is git / What is version control system?
Git Tutorial 1: What is git / What is version control system?
codebasics
45 Git Tutorial 2 : What is Github? | github tutorial
Git Tutorial 2 : What is Github? | github tutorial
codebasics
46 Git Tutorial 4: Basic Commands: add, commit, push
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
47 Git Tutorial 5: Undoing/Reverting/Resetting code changes
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
48 Git Tutorial 6: Branches (Create, Merge, Delete a branch)
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
49 Git Github Tutorial 10: What is Pull Request?
Git Github Tutorial 10: What is Pull Request?
codebasics
50 Git Tutorial 7: What is HEAD?
Git Tutorial 7: What is HEAD?
codebasics
51 Git Tutorial 9: Diff and Merge using meld
Git Tutorial 9: Diff and Merge using meld
codebasics
52 Difference between Multiprocessing and Multithreading
Difference between Multiprocessing and Multithreading
codebasics
53 Python Tutorial - 27. Multiprocessing Introduction
Python Tutorial - 27. Multiprocessing Introduction
codebasics
54 Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
55 Git Tutorial 8 - .gitignore file
Git Tutorial 8 - .gitignore file
codebasics
56 Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
57 Python Tutorial - 30. Multiprocessing Lock
Python Tutorial - 30. Multiprocessing Lock
codebasics
58 Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
59 What is code?
What is code?
codebasics
60 Python unit testing - pytest introduction
Python unit testing - pytest introduction
codebasics

Related Reads

📰
I Asked Claude to Audit My Entire Income Strategy. What It Found Was Uncomfortable.
Using AI to audit income strategy reveals uncomfortable truths, highlighting the importance of objective analysis in personal finance
Medium · AI
📰
7 AI Tools Every Freelancer Should Learn in 2026 (To Work Smarter, Not Harder)
Learn 7 essential AI tools to boost your freelancing career and work smarter, not harder
Medium · AI
📰
How to prepare for Spain civil service TIC exam using AI in 2026
Learn how to leverage AI tools to prepare for the Spain Civil Service TIC exam in 2026, improving your chances of success
Dev.to AI
📰
AI-Powered Sample Clearance: Building Legally-Aware Reports for Independent Producers
Learn how AI-powered sample clearance can help independent music producers navigate copyright risks and create legally-aware reports
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
Up next
14+ Free Google AI Tools for Research & Learning You Should Know
Growth Learner
Watch →