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’.
- Extract text from PDF File using Python
- Python program to extract Email-id from URL text file
- Python - Extract hashtags from text
- Convert Text and Text File to PDF using Python
- Python | Extract numbers from string
- Python | Extract numbers from list of strings
- Python | Extract Numbers in Brackets in String
- Convert Text file to JSON in Python
- Saving Text, JSON, and CSV to a File in Python
- Python | Scramble words from a text file
- Python | Finding 'n' Character Words in a Text File
- Count number of lines in a text file in Python
- Python program to Reverse a single line of a text file
- Python | Count occurrences of each word in given text file (Using dictionary)
- Python | Create an empty text file with current date as its name
- Python program to Count the Number of occurrences of a key-value pair in a text file
- Text Input box with a verification button in kivy (using .kv file)
- Python program to reverse the content of a file and store it in another file
- reStructuredText | .rst file to HTML file using Python for Documentations
- Create a GUI to convert CSV file into excel file using Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.