Task: Write a Python file program read numbers write squares. This Python programming tutorial will explain the Python program with the following statement:
Write a Python program to open an existing text file called “fnumbers.txt” on D drive. It will read each number and calculate its square. Then the program will write the square in another new text file with the name “fsquares.txt” on D drive.
First of all, open notepad software to create a new text file with numbers.
Write down one to seven numbers in this text file.
Select Save option from File menu. Write fnumbers as the name of file in file name text box. Select the file location as D drive. Click on Save button or press Enter simply.
Write the following program in Python IDLE IDE. Save the Python program with a suitable name. Click on “Run module” command in Run menue of the Python IDLE IDE.
If the program executed successfully, you will see another file on D drive
The Source code of Python file program read numbers write squares
The contents of the fsquares.txt file are:
Since the fnumbers.txt file has the following 1 to seven numbers
How this program works?
- Write a Python program to open an existing file fnumbers.txt from D drive.
- The program will read numbers from this file
- and write the squares of every number in a new file fsquares.txt on D drive.
- open fnumbers.txt file in read mode
- create a new file fsquares.txt with “w” mode
- use a for loop to read a number
- and calculate and write its square in fsquares.txt file
- close the files
You may also like to read:
Write a Python file program read numbers write squares.
Python Text File Read and Show Contents Program
Python Text File Read and Display file data with Exception Handling FileNotFoundError
Python File Program Count Characters in Text File
Python Text File Program To Count Vowels