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.
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.
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.
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’.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.