Write a program to store water usage data of 4 customers in a text file. The program asks the user to enter account number, customer type (R for residential or B for business), and number of gallons used for each of the 4 customers. Store the data in a text file named "water.txt". Overwrite old data in "water.txt" if the file already exists. The following is an example.
Enter account number: 3147
Enter R for residential, B for business: R
Enter number of gallons used: 1000
Enter account number: 2168
Enter R for residential, B for business: R
Enter number of gallons used: 6002
Enter account number: 5984
Enter R for residential, B for business: B
Enter number of gallons used: 2000
Enter account number: 7086
Enter R for residential, B for business: B
Enter number of gallons used: 8002
The example above writes the following data to the file "water.txt":
3147 R 1000
2168 R 6002
5984 B 2000
7086 B 8002
Please answer with code i can use with pycharm for python programming?

Respuesta :

Answer:

The program for this question can be given as:

Program:

def main():

    f= open("water.txt","w+")

    for i in range(4):

        f.write(input('Enter account number:\r\n'))

        f.write(input('Enter R for residential,B for business:\r\n'))

        f.write(input('Enter number of gallons used:\r\n'))

    f.close()    

if __name__== "__main__":

 main()

Output:

Enter account number:12

Enter R for residential,B for business:R

Enter number of gallons used:12345

Enter account number:13

Enter R for residential,B for business:B

Enter number of gallons used:8906

Enter account number:11

Enter R for residential,B for business:B

Enter number of gallons used:56789

Enter account number:10

Enter R for residential,B for business:R

Enter number of gallons used:12348

create a file water.text

12R12345

13B8906

11B56789

10R12348

Explanation:

In the above python program firstly we define the main function in this function we use the f.open() function. This function helps to open a file, and returns its values as a file object. In this function, we pass the file name and mode that is "water.txt" and "w+". The "w+" mode is used for writing mode and  If the file does not exist then it will create a new file and "+" is used for reading and writing (updating) the file. Then we will use the input() function. This function helps to take input from the user. then we will close the file and end the main function.