Python program to read a text file line by line and display each word separated by a #|Python program to read a text file line by line and perform specific functions|Text File operations in python.
Introduction
In this python program, we will learn how to;-
- Read a text file
- Separate every word and add a "#" after each word
- print the result
Their are many methods to perform this task.
In this page We will show you two standard approaches for performing the task.
1)By using "For" loop
2)By using readline().
1st -By using readline( ).
Code:-
#Note you have to paste the path of text file in the following code as directed.
Openedfile=open("Paste path of your file",'r')
reading=Openedfile.readline()
Split=reading.split()
newline=""
for i in Split:
newline=newline+i+'#'
print(newline)
#-----------------CODE ENDED-----------------
Source File:-
Output:-
Executed On pydroid3 |
2nd -By using " for " loop-
Code:-
file=open(r"paste path of your file","r")
item=[]
for i in file:
splitwords=i.split()
for m in splitwords:
item.append(m)
print("#".join(item))
#Code ends
About the Code-
- You have to paste the path of your file in line 1 as directed.otherwise it can give an error.
WORKING of first code:-
- The readline() method returns one line from the file.
- Split function separates the words and returns a list .
- for loop is used so that every word is taken after each iteration from the list.
- after adding a "#" finally print line is executed.
Difference between Readline() and readlines():
readline():-
- This method will read one line at a time .
- A new line character is left at the end of the every line and is ignored for the last line in the file.
- if specified or run in loop his method reads up to the end of the line with readline() and returns a list.
readlines():-
- This method will read all the lines in the file at a time.
- This method reads all the content of file and stores it in the form list.
- This method reads up to the end of the line with readline () and returns a list.
"Hope it helped"
Have anything in mind? Let me
know in the comment section👇
Have anything in mind? Let me
know in the comment section👇