View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to
operate on files. Data file handling in Python is done in two types of files:
- Text file [.txt extension]
- Binary file [.bin extension]
Here we are operating on the .txt file in Python. Through this program, we can extract numbers from the content in the text file and add them all and print the result.
Approach
Reading the contents of the file, we will match the characters’ type against int. If
the result of equality is true, then the number will be added to the number stored in the memory allocated to the variable ‘a’. We initiate the variable ‘a’ here with the value 0.
Python3
file
=
open
[
'GFG.txt'
,
'w'
]
data
=
'Geeks1 f2or G8e8e3k2s0'
file
.write[data]
file
.close[]
Using the above code, we opened a new file named ‘GFG’ in write mode.
Using, the write[] function we inserted the data allocated to the variable data in the memory. After this, we closed the file.
Reading from the above-created file and extracting the integers.
Python3
h
=
open
[
'GFG.txt'
,
'r'
]
content
=
h.readlines[]
a
=
0
for
line
in
content:
for
i
in
line:
if
i.isdigit[]
=
=
True
:
a
+
=
int
[i]
print
[
"The sum is:"
, a]
Output:
The sum is: 24
The above program emphasizes on extracting the numbers from the content stored in the text file named ‘GFG’. Furthermore, the numbers are then added after typecasting and stored in the variable ‘a’.
I have a simple .txt file named cart.txt that has 4 lines of text and numbers and all separated by commas i.e.
23453, 1, 45.64, white, gloves
25753, 2, 78.32, red, bag
23346, 1, 24.54, blue, club
87653, 4, 76.12, green, ball
I need to extract out the price and then sum the total. So far I have:
with open["cart.txt", "r"] as text_file:
for line in text_file:
part, quantity, price, desc1, desc2 = line.split[", "][2]
total = sum[[float[price] for price in line]]
print["The total price for the awesome Fathers Day gifts you bought is ${}".format[total]]
When I run the program I get an error saying that python can not convert a str to a float: ','.
If I remove the part, quantity, etc and do a
print on that line that contains line.split, I receive all 4 prices without any commas at the end. Why is python adding the comma back in which is not allowing me to convert it to a float? Any help is much appreciated.
This is a Python Program to read a text file and print all numbers present in the text file. Problem Description The program takes the name of a file from the user and prints all the numbers present in the text file. Problem Solution 1. Take the file name from the user. Program/Source Code Here is source code of the Python Program to print all the numbers present in a text file. The program output is also shown below.
2. Read each line from the file and split the line to form a list
of words.
3. Use a for loop to traverse through the words in the list and another for loop to traverse through the letters in the word.
3. Check if the letter provided by the user is a digit and if it is, print it.
4. Exit.
fname = input["Enter file name: "] with open[fname, 'r'] as f: for line in f: words = line.split[] for i in words: for letter in i: if[letter.isdigit[]]: print[letter]
Program Explanation
1. User must enter a file name.
2. The file is
opened using the open[] function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split[].
5. A for loop is used to traverse through the words list and another for loop is used to traverse through the letters in the word.
6. If the letter encountered is a digit, the digit is printed.
Runtime Test Cases
Case 1: Contents of file: hello world hello5 hello6 Output: Enter file name: out.txt 5 6 Case 2: Contents of file: hello world7 test2 test test8 Output: Enter file name: out1.txt 7 2 8
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
Next Steps:
- Get Free Certificate of Merit in Python Programming
- Participate in Python Programming Certification Contest
- Become a Top Ranker in Python Programming
- Take Python Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.
Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.