Тёмный

Python Tutorial - 13. Reading/Writing Files 

codebasics
Подписаться 1,1 млн
Просмотров 186 тыс.
50% 1

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: github.com/codebasics/py/blob...
Exercise: github.com/codebasics/py/blob...
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 codebasics.io/ for my affordable video courses.
Next Video:
14. if _name_ == "__main__": • 14. if __name__ == "__...
Website: codebasics.io/
Facebook: / codebasicshub
Twitter: / codebasicshub

Опубликовано:

 

28 июн 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 131   
@codebasics
@codebasics 2 года назад
Do you want to learn python from me with a lot of interactive quizzes, and exercises? Here is my project-based python learning course: codebasics.io/courses/python-for-beginner-and-intermediate-learners
@agamcheema4361
@agamcheema4361 Год назад
do this mention paid course of code basic is having same videos or extra lectures are been provide in that?Any one can answer
@smaransure2234
@smaransure2234 Месяц назад
8 years ago and still reliable is pretty awesome
@codebasics
@codebasics 3 года назад
Here is the link of exercise along with the solution, please work on it as it will make your learning solid: github.com/codebasics/py/blob/master/Basics/Exercise/13_read_write_files/read_write_file_exercise.md
@thebaka234
@thebaka234 3 года назад
thanks for the tot :)
@real_twanniefanclub8800
@real_twanniefanclub8800 4 года назад
The best tutorial I've ever seen
@FurqaanShafi
@FurqaanShafi 6 лет назад
ur vids r great to watch...ty fr such great wrk
@dig3476
@dig3476 6 лет назад
Thanks for this great video, you helped me for my assignment
@nastaran1010
@nastaran1010 7 месяцев назад
Thank you so much. you are the best teacher I've even seen. Good luck.
@codebasics
@codebasics 7 месяцев назад
Thank you so much for your kind words.
@bikonkumardas
@bikonkumardas 3 года назад
The easiest one on youtube! Loved it..
@user-fq2nd8nw6f
@user-fq2nd8nw6f 4 года назад
thanks for a clear demonstration !!
@ethan073
@ethan073 6 лет назад
Very good, thank you! The background music was a nice addition too :)
@bobbysteakhouse7022
@bobbysteakhouse7022 5 лет назад
no it wasn't. It really wasn't
@farheenanjum
@farheenanjum 2 года назад
The background music is so irritating... I am unable to understand the main concepts
@trodutorio
@trodutorio 6 лет назад
Thanks from Brasil!
@evolutionoftastebuds5817
@evolutionoftastebuds5817 4 года назад
thank you ...finally i got it
@aswins1862
@aswins1862 6 лет назад
Good job
@abdevilliers7744
@abdevilliers7744 5 лет назад
Then that has a special meaning and it will not work 👌👌👌👌 What an explanation
@REAVER_Game
@REAVER_Game 7 лет назад
thank you from Russia !
@nazmulhossain660
@nazmulhossain660 5 лет назад
Very Nice
@Ishaan_Garud
@Ishaan_Garud 4 года назад
Thank you from India, MAHARASHTRA
@Codenza
@Codenza 4 года назад
You really good to explain thank you
@codebasics
@codebasics 4 года назад
I am glad you liked it
@Codenza
@Codenza 4 года назад
@@codebasics yes of course, easy and great way to explain, we hope realy if you do a video to explain working working with kivymd in python. thyank you
@reviewguru827
@reviewguru827 Год назад
Hi Sir, Love your content as always...great video.. I have few questions regarding the example you have taken in this video: If expand the conversation in the example taken Using text file handling and string manipulation in python 1) How can I find the number of unique speaker and list of all speaker present in file and also want separate file for each speaker. 2) I want to find the list of all unique words spoken by each unique speaker in new line and want to save these words in respective speaker's file . 3) how to remove all punctuations. If I will get the answer it will be great help. Thanks in advance....
@jaggyjut
@jaggyjut 2 года назад
Great explanation. Would you be able to create a tutorial on reading values in a text file using splitlines, previous_lines nested in a for loop. Basically how to take field name & respective value from a text file and output them into a pandas dataframe.
@riyaprem1434
@riyaprem1434 3 года назад
Sir can u explain why u have used Double slash in path here but only single slash for path when we were dealing with modules
@younessaznag470
@younessaznag470 2 года назад
Thanks a lot man for helping us, and i wish that allah help you also.
@jomarcristianerandio9755
@jomarcristianerandio9755 5 лет назад
Hi sir, you're tutorial is very educating, do you know how to delete a letter in a text file?
@sabuein
@sabuein 3 года назад
Thank you.
@codebasics
@codebasics 3 года назад
☺️👍
@Nipulpatel143
@Nipulpatel143 3 года назад
Great
@sheikhabdullah8298
@sheikhabdullah8298 Год назад
Thank you Sir. There is a procedural bug. The previous tutorial should have come after this one. Kindly adjust the playlist.
@devesh_upreti
@devesh_upreti Год назад
solution: def Countnum(num): k = open("C:\\input.txt") number = k.readlines() number = [x.strip() for x in number] count =0 for i in number: if i.__contains__(str(num)): count = count +1 print(count)
@swayamgupta7972
@swayamgupta7972 2 года назад
Sir I love you
@nidhijha8357
@nidhijha8357 2 года назад
Great explain txt extension sy xls m change kr skty hai??
@nikhilkatnour1749
@nikhilkatnour1749 5 лет назад
must watch
@yashdeepy4060
@yashdeepy4060 4 года назад
Can you please share solution for sample exercise? Thanks.
@olgaggg
@olgaggg Год назад
Hi, in the exercise section solution to 1st problem linked to wrong link (when you press it open solution for problem 2)
@aryalvai2265
@aryalvai2265 5 лет назад
How to read a text file which are content in 2D array and find out the some value from that array. For example. Name and phone number. I want to search certain name and it's corresponding phone number
@chineduokpala784
@chineduokpala784 2 года назад
Hi, I cannot perform this action using a macbook/apple computer. Are there additional instructions for Mac users?
@work-dw2hl
@work-dw2hl 3 года назад
for exercise 1 and 2 you put the same solution please change that one
@jitendergupta2240
@jitendergupta2240 2 года назад
Hello sir, logic of 2nd question is :- for x in file: word = x.split() calc = int(word[0][0])+int(word[0][2]) print("sum is", calc) and it is working and fine buts ir i want another soln for this, shall you provide that?
@ananthnarayan5631
@ananthnarayan5631 3 года назад
i have created an python GUI application where Entry widget, which takes user input to create ,>>new folders>> but images should get saved in that particular file which user have created .
@agamcheema4361
@agamcheema4361 Год назад
do that mention paid course of code basic is having same videos. or extra lectures are been provide in that?Any one can answer
@mohitsinghbais361
@mohitsinghbais361 3 года назад
Sir.. solution of problem 1 is missing can you please check and confirm in exercise section
@shivanshusharma20.07
@shivanshusharma20.07 5 лет назад
why you have written "str" in print(str(tokens))?
@asitkumar9410
@asitkumar9410 Год назад
I have doubt in the solution given for stocks exercise In the last line that is line#12 of solution, how f and variables has used. Can someone give more insights on this please. any link or reference would be helpful --> out.write(f"{stock},{pe},{pb} ")
@barshasinha3137
@barshasinha3137 6 лет назад
hi , great video. But I have one doubt. I didn't see any ' ' in the last solution. you just shuffled the code which will display the word count first followed by the line. what if we want to display the line first followed by word count.
@dharmeshtiwari09
@dharmeshtiwari09 3 года назад
Using rsplit() method
@srinivaskadiyala
@srinivaskadiyala Год назад
first: f.open, then f_out.open but while closing f.close and f_out.close - shouldnt it be "f_out.close then f.close" ?
@znadaara
@znadaara 3 года назад
what mean for line "in" I didn't understand why we use "in"?
@salinakhadka9743
@salinakhadka9743 Год назад
solution 2: f=open("C:\\Users\\salina\\Desktop\\mypy\\input.txt","r") f_out=open("C:\\Users\\salina\\Desktop\\mypy\\input_1.txt","w") for line in f: cl=line.split(",") # changes the file contents(string) to list ,as two numbers are separated with comma so we are using comma total="The sum is : "+str(int(cl[0])+int(cl[1]))+" | "+line+" " f_out.write(total)
@shanipratapsingh2300
@shanipratapsingh2300 6 лет назад
Hi, Pls help, How to read a file and get desired output . eg : File have some content "abc;xyz|,:1;tug,jd;98d;dea;wes;de5;2018;df" want result like :- "; separated 4th field"
@legacyuser9665
@legacyuser9665 4 года назад
tanks you from iraq
@codebasics
@codebasics 4 года назад
Thanks legacy for the comment. 😊👍
@himasaiprakashmedicharla6747
@himasaiprakashmedicharla6747 4 месяца назад
in the problem. "w" method is used why the text is not over written? pls explain
@vishalbansode8634
@vishalbansode8634 4 года назад
Can you give the solution for both the questions. I tried but I didn't got the logic def countnum(f, x): count = 0 for line in f: if line == x: count = count + 1 else: print("Number not found") return count x = int(input("Enter no.")) f = open("C:\\Users\\Win10\\Desktop\\funny.txt", "r") countnum(f, x,)
@RM-lb7xw
@RM-lb7xw 3 года назад
Here's the solution for the first question: def countNum(num): count = 0 for line in f.readlines(): line = line.replace(" ", "") if str(num) in line.split(','): count += 1 return count f = open("C:/Users/Desktop/input.txt", "r") num_to_count = input("Enter number to count: ") occurences = countNum(num_to_count) print(occurences) f.close() For the second one: f = open("C:/Users/Desktop/input.txt", "r") file_content = f.readlines() f.close() f = open("C:/Users/Desktop/input.txt", "w") for line in file_content: addition = 0 line = line.replace(" ", "") num_list = line.split(',') for num in num_list: addition += int(num) f.write("Sum: " + str(addition) + " | " + num_list[0] + "," + num_list[1] + " ") f.close() Hope that helps.
@nainagupta4949
@nainagupta4949 Год назад
i am unable to understand why i am not getting the lines in the console although the file has lines
@rafy-ivanmorales3077
@rafy-ivanmorales3077 2 года назад
I’m a new student and need help to do this project: I have a port scanner script it works properly, it works in Pycharm using python3.9. I have to make a file and I did make call (Example.txt) On this file, I have to do this: 3. If the Ports is open, it should create a file and add an entry for port number 4. In case of any exception for instance “host is not available”, “host name could not be resolved” or due to any other error, you need to write that exception into the same file. I’m not asking for you to do the project for me, I'm only asking ware I need to work or used in my script to accomplish this because it is my first time doing this and working with python too, and I have been struggling with this part one very bad. I can even send you the code, so you can look and only tell me what I’m doing bad, is not working.
@user-fo7fn2ll6o
@user-fo7fn2ll6o Год назад
Solution 2: # Read values from the file with open('c:\\xampp\\exersize_wp.txt', 'r') as file: lines = file.readlines() print(lines) # Process each line output = [] for line in lines: # Extract the numbers from the line numbers = line.strip().split(',') num1 = int(numbers[0]) print(num1) num2 = int(numbers[1]) print(num2) # Calculate the sum total = num1 + num2 # Create the output string output.append(f'sum: {total} | {num1},{num2}') print(output) # Write the output to a file with open('c:\\xampp\\output_wp.txt', 'w') as file: file.write(' '.join(output))
@sivachaithu3381
@sivachaithu3381 3 года назад
Sir, I have one python app but your said program not execute in python app
@amitbajpai6265
@amitbajpai6265 6 лет назад
Can you please give me the code of first question of the exercise.
@kumarking4058
@kumarking4058 2 года назад
Why the lines aren't overwritten in the file when we have used in for write mode-'w'...
@shubhamtiwari7704
@shubhamtiwari7704 3 года назад
For line in f: In above is line a keyword? If not how python knows by mentioning line that it has to go line by line Please anyone explain this
@prajnakarnik
@prajnakarnik 3 года назад
It is not the key word: "line", even when you use any other key word, the same thing happens. Thanks to inbuilt function: readline() in Python for this phenomenon. readline() function reads a line of the file and return it in the form of the string. It takes a parameter n, which specifies the maximum number of bytes that will be read. However, does not reads more than one line, even if n exceeds the length of the line. readline() returns the next line of the file which contains a newline character in the end.
@saipavan3182
@saipavan3182 6 лет назад
try 1.5x
@VaghelaDhruven
@VaghelaDhruven Месяц назад
you have to change this video at 15th rank and working with json after this,
@starman8505
@starman8505 2 года назад
thanks , got a new excuse, there are many schools in the path 🤣🤣
@ArpitDharmshaktu
@ArpitDharmshaktu 13 дней назад
will everything will be same on macbook too?
@jullien191
@jullien191 3 года назад
जाय जाय
@salinakhadka9743
@salinakhadka9743 Год назад
solution 1: f=open("C:\\Users\\salina\\Desktop\\mypy\\input.txt","r") occur=f.read() def countNum(n): c=0 for num in occur: if n in num: c=c+1 return c user=input("Enter a number: ") res=countNum(user) print(res) f.close()
@parulchoudhary629
@parulchoudhary629 3 года назад
No files are seen in c drive
@dharmeshtiwari09
@dharmeshtiwari09 3 года назад
The new line character at end of every line is property of file..... We need to remove that be rsplit()..... I think you should have told this method instead of appending wordcount at beginning.
@tcholly
@tcholly 4 года назад
OSError: [Errno 9] Bad file descriptor what's that?
@legacyuser9665
@legacyuser9665 4 года назад
griat toturiel, my techer tel me my werk is veri griat
@codebasics
@codebasics 4 года назад
👍😊
@javed5184
@javed5184 Год назад
Hello Sir, when I run this tutorial exercise 13 of stock.csv the error shows- price = float(tokens[1]) IndexError: list index out of range Pls giude
@codebasics
@codebasics Год назад
check tokens list. Looks like it doesnt have an element at index 1
@waqasmuhammad9232
@waqasmuhammad9232 4 года назад
Sir 2nd practice question question is giving error as per your pdf solution.
@codebasics
@codebasics 4 года назад
What error?
@waqasmuhammad9232
@waqasmuhammad9232 4 года назад
@@codebasics unable to find your email address. Kindly share please.
@zakinthebox5963
@zakinthebox5963 5 лет назад
What is the program you use for python programming?
@sapathchakraborty
@sapathchakraborty 3 месяца назад
huh?
@engrnasirshah4426
@engrnasirshah4426 4 года назад
Sir. which python book did you recommend for us
@codebasics
@codebasics 4 года назад
Hello, I actually never read any book on python. I learnt python from online tutorials, reading articles and then practicing it.
@engrnasirshah4426
@engrnasirshah4426 4 года назад
@@codebasics Sir. i need it for my final project .Sir. there is any suggestion for me to follow a link or some other material.thank's
@codebasics
@codebasics 4 года назад
@@engrnasirshah4426 Here is a list that you can refer to. I wish you all the best for your project. realpython.com/best-python-books/
@kostasnikoloutsos5172
@kostasnikoloutsos5172 7 лет назад
What background music is this?
@simransangha2887
@simransangha2887 4 года назад
Its called "annoying" just searched the web :P
@afrozkhan.
@afrozkhan. 3 года назад
can you please clear assignment Qn s
@mauricioluisvega8342
@mauricioluisvega8342 4 года назад
but, if i wants write from the keyboard into a file?
@IRedBerryI
@IRedBerryI 3 года назад
File.write(variable) and beforehand do variable = input('')
@damn204
@damn204 5 лет назад
🤣😂 that "special thing" was awefull bye!
@techglow4302
@techglow4302 3 года назад
Solution 1: with open("C:\\codefile\\ownfile.txt", "r") as f: count=0 s=f.read() for line in s: if '9' in line: count= count+1 print(count)
@vineetdadheech4938
@vineetdadheech4938 Год назад
How would this even work when you didn't use split() for the words to get a list of words.
@premmishra7590
@premmishra7590 3 года назад
sir, I have a doubt . plz tell how i contect with you
@time968
@time968 4 года назад
how far this is suitable for data analyst?
@codebasics
@codebasics 4 года назад
Very much relavant because as a data analyst you would be processing files a lot.
@anandthakkar6109
@anandthakkar6109 3 месяца назад
what to do if I havea mac
@Ishaan_Garud
@Ishaan_Garud 4 года назад
how to do it on Android
@shreyashtapare
@shreyashtapare 2 года назад
sir Yo have to Interchange 15 And 14 Video
@rishabhrai8404
@rishabhrai8404 6 лет назад
+codebasics , very important advice for you, your content is good enough , but please don't include background music, that's kind a ruining your video, please take this advice seriously
@dutta.alankar
@dutta.alankar 7 лет назад
Can you please make a tutorial on reading data stored in Unformatted Fortran Binary in Python and ploting them? Such files are often created in many Physics simulations like the extremely famous Gadget 2 Galaxy Evolution Simulation program.
@dutta.alankar
@dutta.alankar 7 лет назад
By the way, I absolutely loved your tutorials and the simplicity with which you presented it.
@dutta.alankar
@dutta.alankar 7 лет назад
stackoverflow.com/a/41411716/5074755 Thanks for following up so quickly. Please have a look at this if you manage some time out of your busy schedule. I did this after going through your tutorials and encountered problems.
@dutta.alankar
@dutta.alankar 7 лет назад
I see. Many thanks.
@sankararao7563
@sankararao7563 2 года назад
You could have used context manager. You could avoid closing of file
@rincymols2763
@rincymols2763 3 года назад
I got permission denied error😥
@seshuac
@seshuac 3 года назад
with open ("question2 file path") as file1: with open("c:\\data\\funny3.txt","w") as file2: for lines in file1: lines.split() total = 0 for number in lines: if number.isalnum(): total += int(number) file2.write(str(total) + " | " + lines)
@amra.haleem5175
@amra.haleem5175 2 года назад
Hello. Please remove the background music and keep this video like the rest videos. Thanks indeed.
@nuruljanah9621
@nuruljanah9621 6 лет назад
please its not working on my python27. please help
@user-tt1ji4bz3c
@user-tt1ji4bz3c 3 года назад
You love JavaScript, C++, PHP, but not python? XD
@bidyutbisal6153
@bidyutbisal6153 2 года назад
Request you to remove background music from video.
@da_ta
@da_ta 4 года назад
Sorry very poor sound
@codebasics
@codebasics 4 года назад
Hey D Tadesse. I apologise for inconvenience. I will make sure to upload video with good quality only.
@senguptagupta7325
@senguptagupta7325 4 года назад
Background music is irritating
@codebasics
@codebasics 4 года назад
Video playlist without background music: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-eykoKxsYtow.html
@techtacular2722
@techtacular2722 24 дня назад
only one question, did u really thought the teacher frank joke was funny?
@user-ss9pm6wc1s
@user-ss9pm6wc1s Год назад
the music is annoying
Далее
READING & WRITING DATA INTO FILES - PYTHON PROGRAMMING
18:50
13. Working With JSON [Python 3 Programming Tutorials]
8:42
Learn Python With This ONE Project!
55:04
Просмотров 1,6 млн
5 Useful F-String Tricks In Python
10:02
Просмотров 268 тыс.
Functions in Python are easy 📞
10:38
Просмотров 405 тыс.
Python Beginner Tutorial #9 - File Operations
15:39
Просмотров 29 тыс.