CodeSolved

Solved Programming Questions & Exercises

Print and save the message in the text file to a specified number

Practice Easy 1965/ Download 290 Views

Write a program that receives the following inputs:

  1. Name of a text file with extension.txt(This is optional input)
  2. The number of times the message should be printed (an integer).
  3. The text that needs to be printed and stored if there is a file.

The task of the program is to print the entered message to the specified number and if the file name is entered, add the same messages to the end of the file with the suffix.txtSave.

For example, if the inputs are as follows:

name file: example.txt
chap range: 10
text: amirhn.ir

The program output should be as follows:

amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir
amirhn.ir

Also textamirhn.ir2 times to the end of the fileexample.txtWill be added.

Note that if the file name is not entered, the program will only print the messages and no file will be created or edited.

2 Answers

file_name = input("name file: ").strip()
count = int(input("chap range: "))
text = input("text: ")

for _ in range(count):
    print(text)

if file_name:
    with open(file_name, "a", encoding="utf-8") as f:
        for _ in range(count):
            f.write(text + "\n")
Ai Download Python
range_number = int(input('Enter your range number: >>')) # Get user range number
text = input('Enter your text: >>') # Get user text to write to file

with open('text.txt',"a") as file: # File operations
    for _ in range(range_number):
        file.write(text+"\n")
Mrfasihi Download Python

Submit answer

Submitting answers is currently unavailable.

×
×
Close