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
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.
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)
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))
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
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.
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....
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)
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.
@@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
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()
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 .
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)
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,)
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.
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} ")
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"
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.
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?
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
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.
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.
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.
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)
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
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.
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)
+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
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.
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.
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
do this mention paid course of code basic is having same videos or extra lectures are been provide in that?Any one can answer
8 years ago and still reliable is pretty awesome
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.
Thank you so much. you are the best teacher I've even seen. Good luck.
Thank you so much for your kind words.
Then that has a special meaning and it will not work
👌👌👌👌
What an explanation
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)
Very good, thank you! The background music was a nice addition too :)
no it wasn't. It really wasn't
The background music is so irritating... I am unable to understand the main concepts
The easiest one on youtube! Loved it..
The best tutorial I've ever seen
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()
thank you from Russia !
ur vids r great to watch...ty fr such great wrk
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))
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()
Thanks for this great video, you helped me for my assignment
Thanks from Brasil!
Thank you from India, MAHARASHTRA
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.
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
thanks for a clear demonstration !!
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....
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)
Thank you Sir. There is a procedural bug. The previous tutorial should have come after this one. Kindly adjust the playlist.
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.
Thanks a lot man for helping us, and i wish that allah help you also.
thank you ...finally i got it
That was a funny joke. Thank you. 😃😃
Hi, I cannot perform this action using a macbook/apple computer. Are there additional instructions for Mac users?
You really good to explain thank you
I am glad you liked it
@@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
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()
Great explain txt extension sy xls m change kr skty hai??
Hi, in the exercise section solution to 1st problem linked to wrong link (when you press it open solution for problem 2)
in the problem. "w" method is used why the text is not over written? pls explain
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 .
Good job
do that mention paid course of code basic is having same videos. or extra lectures are been provide in that?Any one can answer
Very Nice
Can you please share solution for sample exercise? Thanks.
thanks , got a new excuse, there are many schools in the path 🤣🤣
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)
i am unable to understand why i am not getting the lines in the console although the file has lines
Thank you.
☺️👍
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,)
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.
Sir.. solution of problem 1 is missing can you please check and confirm in exercise section
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}
")
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"
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.
Using rsplit() method
Why the lines aren't overwritten in the file when we have used in for write mode-'w'...
Hi sir, you're tutorial is very educating, do you know how to delete a letter in a text file?
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)
How would this even work when you didn't use split() for the words to get a list of words.
Sir 2nd practice question question is giving error as per your pdf solution.
What error?
@@codebasics unable to find your email address. Kindly share please.
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
check tokens list. Looks like it doesnt have an element at index 1
Sir, I have one python app but your said program not execute in python app
Great
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?
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
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" ?
what mean for line "in" I didn't understand why we use "in"?
Sir I love you
will everything will be same on macbook too?
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
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.
for exercise 1 and 2 you put the same solution please change that one
sir, I have a doubt . plz tell how i contect with you
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?
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.
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.
why you have written "str" in print(str(tokens))?
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)
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
thanks for the tot :)
What background music is this?
Its called "annoying" just searched the web :P
tanks you from iraq
Thanks legacy for the comment. 😊👍
No files are seen in c drive
जाय जाय
OSError: [Errno 9] Bad file descriptor
what's that?
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.
must watch
Can you please give me the code of first question of the exercise.
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)
What is the program you use for python programming?
huh?
Sir. which python book did you recommend for us
Hello, I actually never read any book on python. I learnt python from online tutorials, reading articles and then practicing it.
@@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
@@engrnasirshah4426 Here is a list that you can refer to. I wish you all the best for your project. realpython.com/best-python-books/
+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
but, if i wants write from the keyboard into a file?
File.write(variable) and beforehand do variable = input('')
you have to change this video at 15th rank
and working with json after this,
Hello. Please remove the background music and keep this video like the rest videos. Thanks indeed.
can you please clear assignment Qn s
try 1.5x
🤣😂 that "special thing" was awefull bye!
I got permission denied error😥
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.
By the way, I absolutely loved your tutorials and the simplicity with which you presented it.
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.
I see. Many thanks.
You could have used context manager. You could avoid closing of file
what to do if I havea mac
ITS the ide that matters.not OS
how far this is suitable for data analyst?
Very much relavant because as a data analyst you would be processing files a lot.
how to do it on Android
griat toturiel, my techer tel me my werk is veri griat
👍😊
You love JavaScript, C++, PHP, but not python? XD
sir Yo have to Interchange 15 And 14 Video
Request you to remove background music from video.
only one question, did u really thought the teacher frank joke was funny?
Sorry very poor sound
Hey D Tadesse. I apologise for inconvenience. I will make sure to upload video with good quality only.
the music is annoying
please its not working on my python27. please help
Background music is irritating
Video playlist without background music: ua-cam.com/video/eykoKxsYtow/v-deo.html