Python Tutorial - 13. Reading/Writing Files

Поділитися
Вставка
  • Опубліковано 4 січ 2025

КОМЕНТАРІ •

  • @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 місяців тому +5

    8 years ago and still reliable is pretty awesome

  • @dorisosuagwu
    @dorisosuagwu 3 місяці тому +2

    For those who couldn't find the C: data directory as mentioned on 0:25, you could just create a folder in your local disk (C:), then continue with the lesson to open with the new folder name and whatever you want to write in it.

  • @nastaran1010
    @nastaran1010 Рік тому +2

    Thank you so much. you are the best teacher I've even seen. Good luck.

    • @codebasics
      @codebasics  Рік тому +1

      Thank you so much for your kind words.

  • @abdevilliers7744
    @abdevilliers7744 5 років тому +1

    Then that has a special meaning and it will not work
    👌👌👌👌
    What an explanation

  • @devesh_upreti
    @devesh_upreti Рік тому +1

    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)

  • @ethan073
    @ethan073 6 років тому +9

    Very good, thank you! The background music was a nice addition too :)

    • @bobbysteakhouse7022
      @bobbysteakhouse7022 5 років тому +7

      no it wasn't. It really wasn't

    • @Rise_Reflect
      @Rise_Reflect 2 роки тому +1

      The background music is so irritating... I am unable to understand the main concepts

  • @bikonkumardas
    @bikonkumardas 3 роки тому

    The easiest one on youtube! Loved it..

  • @real_twanniefanclub8800
    @real_twanniefanclub8800 4 роки тому

    The best tutorial I've ever seen

  • @antojero791
    @antojero791 3 місяці тому +2

    problem 2:
    f=open("input.txt","r")
    for x in f:
    word = x.split(",")
    tot=0
    for j in word:
    tot=tot+int(j)
    print("sum:",tot)
    f.close()

  • @REAVER_Game
    @REAVER_Game 8 років тому +4

    thank you from Russia !

  • @FurqaanShafi
    @FurqaanShafi 6 років тому +3

    ur vids r great to watch...ty fr such great wrk

  • @JAIMINPANCHAL-i6m
    @JAIMINPANCHAL-i6m Рік тому

    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))

  • @igormarkaryan
    @igormarkaryan 5 місяців тому +2

    Here is the solution
    for line in f:
    words = line.strip().split() # Remove trailing newline and split into words
    word_count = len(words)
    f_out.write(line.strip() + " wordcount " + str(word_count) + "
    ") # Append word count and newline

    f.close()
    f_out.close()

  • @dig3476
    @dig3476 7 років тому +1

    Thanks for this great video, you helped me for my assignment

  • @trodutorio
    @trodutorio 7 років тому +1

    Thanks from Brasil!

  • @Ishaan_Garud
    @Ishaan_Garud 4 роки тому

    Thank you from India, MAHARASHTRA

  • @srikanth63061095
    @srikanth63061095 Місяць тому

    at 13:20 you should have opened the file for writing data in append mode rather than 'w' mode. I am not sure why the data is not overwritten in the for loop.

  • @riyaprem1434
    @riyaprem1434 4 роки тому +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

  • @user-fq2nd8nw6f
    @user-fq2nd8nw6f 4 роки тому

    thanks for a clear demonstration !!

  • @reviewguru827
    @reviewguru827 2 роки тому

    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....

  • @antojero791
    @antojero791 3 місяці тому +1

    problem 1:
    def occur(num):
    f=open("input.txt","r")
    tot=0
    for x in f:
    word = x.split(",")
    for j in word:
    if num==int(j):
    tot=tot+1
    return tot
    f.close()
    val=occur(7)
    print(val)

  • @sheikhabdullah8298
    @sheikhabdullah8298 Рік тому

    Thank you Sir. There is a procedural bug. The previous tutorial should have come after this one. Kindly adjust the playlist.

  • @jaggyjut
    @jaggyjut 3 роки тому +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.

  • @younessaznag470
    @younessaznag470 2 роки тому

    Thanks a lot man for helping us, and i wish that allah help you also.

  • @evolutionoftastebuds5817
    @evolutionoftastebuds5817 4 роки тому

    thank you ...finally i got it

  • @ramlakshman2
    @ramlakshman2 6 місяців тому

    That was a funny joke. Thank you. 😃😃

  • @chineduokpala784
    @chineduokpala784 3 роки тому +1

    Hi, I cannot perform this action using a macbook/apple computer. Are there additional instructions for Mac users?

  • @Codenza
    @Codenza 5 років тому

    You really good to explain thank you

    • @codebasics
      @codebasics  5 років тому +1

      I am glad you liked it

    • @Codenza
      @Codenza 5 років тому

      @@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

  • @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()

  • @nidhijha8357
    @nidhijha8357 3 роки тому

    Great explain txt extension sy xls m change kr skty hai??

  • @olgaggg
    @olgaggg 2 роки тому

    Hi, in the exercise section solution to 1st problem linked to wrong link (when you press it open solution for problem 2)

  • @himasaiprakashmedicharla6747
    @himasaiprakashmedicharla6747 10 місяців тому

    in the problem. "w" method is used why the text is not over written? pls explain

  • @ananthnarayan5631
    @ananthnarayan5631 4 роки тому

    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 .

  • @itsMeAswinS
    @itsMeAswinS 7 років тому +1

    Good job

  • @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

  • @nazmulhossain660
    @nazmulhossain660 6 років тому

    Very Nice

  • @yashdeept
    @yashdeept 4 роки тому +2

    Can you please share solution for sample exercise? Thanks.

  • @starman8505
    @starman8505 3 роки тому

    thanks , got a new excuse, there are many schools in the path 🤣🤣

  • @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)

  • @nainagupta4949
    @nainagupta4949 2 роки тому

    i am unable to understand why i am not getting the lines in the console although the file has lines

  • @sabuein
    @sabuein 3 роки тому

    Thank you.

  • @vishalbansode8634
    @vishalbansode8634 4 роки тому +1

    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 4 роки тому

      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.

  • @mohitsinghbais361
    @mohitsinghbais361 3 роки тому

    Sir.. solution of problem 1 is missing can you please check and confirm in exercise section

  • @asitkumar9410
    @asitkumar9410 2 роки тому

    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}
    ")

  • @shanipratapsingh2300
    @shanipratapsingh2300 7 років тому

    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"

  • @barshasinha3137
    @barshasinha3137 6 років тому +1

    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.

  • @kumarking4058
    @kumarking4058 3 роки тому

    Why the lines aren't overwritten in the file when we have used in for write mode-'w'...

  • @jomarcristianerandio9755
    @jomarcristianerandio9755 6 років тому +1

    Hi sir, you're tutorial is very educating, do you know how to delete a letter in a text file?

  • @techglow4302
    @techglow4302 4 роки тому +5

    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 2 роки тому

      How would this even work when you didn't use split() for the words to get a list of words.

  • @waqasmuhammad9232
    @waqasmuhammad9232 4 роки тому +1

    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.

  • @javed5184
    @javed5184 2 роки тому

    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  2 роки тому

      check tokens list. Looks like it doesnt have an element at index 1

  • @sivachaithu3381
    @sivachaithu3381 4 роки тому

    Sir, I have one python app but your said program not execute in python app

  • @Nipulpatel143_all
    @Nipulpatel143_all 3 роки тому

    Great

  • @jitendergupta2240
    @jitendergupta2240 3 роки тому

    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?

  • @aryalvai2265
    @aryalvai2265 6 років тому

    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

  • @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"?

  • @swayamgupta7972
    @swayamgupta7972 3 роки тому

    Sir I love you

  • @ArpitDharmshaktu
    @ArpitDharmshaktu 6 місяців тому

    will everything will be same on macbook too?

  • @shubhamtiwari7704
    @shubhamtiwari7704 4 роки тому +1

    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 роки тому +1

      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.

  • @work-dw2hl
    @work-dw2hl 3 роки тому +1

    for exercise 1 and 2 you put the same solution please change that one

  • @premmishra7590
    @premmishra7590 3 роки тому

    sir, I have a doubt . plz tell how i contect with you

  • @horriabayan
    @horriabayan 3 місяці тому

    when I try to run
    f = open("c:\\data\\funny.txt",'r')
    f.write('hi')
    f.close()
    it says that there is no directory file,can anyone help me?

    • @dorisosuagwu
      @dorisosuagwu 3 місяці тому

      It means that you do not have the folder 'data' created in your local disk (c:). You have to create a folder in your local disk (c:) and call it data or anything, then continue with the lesson to open with the new folder name and whatever you want to write in it.

  • @rafy-ivanmorales3077
    @rafy-ivanmorales3077 3 роки тому

    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.

  • @shivanshusharma20.07
    @shivanshusharma20.07 6 років тому

    why you have written "str" in print(str(tokens))?

  • @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)

  • @codebasics
    @codebasics  4 роки тому +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

  • @kostasnikoloutsos5172
    @kostasnikoloutsos5172 7 років тому +2

    What background music is this?

    • @simransangha2887
      @simransangha2887 4 роки тому

      Its called "annoying" just searched the web :P

  • @legacyuser9665
    @legacyuser9665 5 років тому

    tanks you from iraq

    • @codebasics
      @codebasics  5 років тому

      Thanks legacy for the comment. 😊👍

  • @parulchoudhary629
    @parulchoudhary629 3 роки тому +1

    No files are seen in c drive

  • @jullien191
    @jullien191 4 роки тому

    जाय जाय

  • @tcholly
    @tcholly 5 років тому

    OSError: [Errno 9] Bad file descriptor
    what's that?

  • @dharmeshtiwari09
    @dharmeshtiwari09 4 роки тому

    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.

  • @nikhilkatnour1749
    @nikhilkatnour1749 6 років тому

    must watch

  • @amitbajpai6265
    @amitbajpai6265 6 років тому

    Can you please give me the code of first question of the exercise.

  • @KartikKumar-ef5kc
    @KartikKumar-ef5kc 4 місяці тому

    Here is a solution I came out with,
    def countNum(num):
    count = 0
    store = []
    for line in file:
    # token = line.split(",")
    token = list(line)
    store.append(token)
    print(store)
    # print(store[0])
    for item in store:
    # print(item)
    for n in item:
    # print(n)
    # print(list(n))
    if(str(num) == n):
    count = count +1
    # print("checked")

    for s in range(1):
    f = open("path of your document", "a")
    m = int(item[0])+int(item[2])
    f.write("
    "+"sum : "+ str(m)+ "|"+ item[0]+ ","+ item[2])
    f.close()
    print("Count of number",num,"-> ", count)
    return count;
    with open("path of your document", "r") as file:
    countNum(9)

  • @zakinthebox5963
    @zakinthebox5963 6 років тому

    What is the program you use for python programming?

  • @engrnasirshah4426
    @engrnasirshah4426 5 років тому

    Sir. which python book did you recommend for us

    • @codebasics
      @codebasics  5 років тому +2

      Hello, I actually never read any book on python. I learnt python from online tutorials, reading articles and then practicing it.

    • @engrnasirshah4426
      @engrnasirshah4426 5 років тому

      @@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  5 років тому

      @@engrnasirshah4426 Here is a list that you can refer to. I wish you all the best for your project. realpython.com/best-python-books/

  • @rishabhrai8404
    @rishabhrai8404 7 років тому

    +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

  • @mauricioluisvega8342
    @mauricioluisvega8342 5 років тому

    but, if i wants write from the keyboard into a file?

    • @IRedBerryI
      @IRedBerryI 3 роки тому

      File.write(variable) and beforehand do variable = input('')

  • @VaghelaDhruven
    @VaghelaDhruven 7 місяців тому

    you have to change this video at 15th rank
    and working with json after this,

  • @amra.haleem5175
    @amra.haleem5175 2 роки тому +2

    Hello. Please remove the background music and keep this video like the rest videos. Thanks indeed.

  • @afrozkhan.
    @afrozkhan. 4 роки тому

    can you please clear assignment Qn s

  • @saipavan3182
    @saipavan3182 6 років тому +3

    try 1.5x

  • @damn204
    @damn204 5 років тому +1

    🤣😂 that "special thing" was awefull bye!

  • @rincymols2763
    @rincymols2763 4 роки тому

    I got permission denied error😥

  • @dutta.alankar
    @dutta.alankar 8 років тому

    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 8 років тому

      By the way, I absolutely loved your tutorials and the simplicity with which you presented it.

    • @dutta.alankar
      @dutta.alankar 8 років тому

      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 8 років тому

      I see. Many thanks.

    • @sankararao7563
      @sankararao7563 3 роки тому

      You could have used context manager. You could avoid closing of file

  • @anandthakkar6109
    @anandthakkar6109 9 місяців тому

    what to do if I havea mac

    • @Coral_pepe
      @Coral_pepe 4 місяці тому

      ITS the ide that matters.not OS

  • @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.

  • @Ishaan_Garud
    @Ishaan_Garud 4 роки тому

    how to do it on Android

  • @legacyuser9665
    @legacyuser9665 5 років тому

    griat toturiel, my techer tel me my werk is veri griat

  • @戴鈞彥
    @戴鈞彥 3 роки тому

    You love JavaScript, C++, PHP, but not python? XD

  • @shreyashtapare
    @shreyashtapare 3 роки тому

    sir Yo have to Interchange 15 And 14 Video

  • @bidyutbisal6153
    @bidyutbisal6153 2 роки тому

    Request you to remove background music from video.

  • @techtacular2722
    @techtacular2722 7 місяців тому +1

    only one question, did u really thought the teacher frank joke was funny?

  • @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.

  • @عبداللهالبطريق
    @عبداللهالبطريق 2 роки тому

    the music is annoying

  • @nuruljanah9621
    @nuruljanah9621 7 років тому

    please its not working on my python27. please help

  • @senguptagupta7325
    @senguptagupta7325 5 років тому

    Background music is irritating

    • @codebasics
      @codebasics  5 років тому

      Video playlist without background music: ua-cam.com/video/eykoKxsYtow/v-deo.html