CodeSolved

A comprehensive source of programming questions and exercises

Save information in the file

Practice Easy 11/ Download 2388 Views

Write a program thatStudent Name and NumberReceive users and in a file namedStudents.txtSave. Also, after each storage, display the entire information of this file at the output.

12 Answers

This answer is only visible to premium members
This answer is only visible to premium members
This answer is only visible to premium members
let msg = 'error'
alert(msg) 
This answer is only visible to premium members
This answer is only visible to premium members

This answer is only visible to premium members

Subscription is currently unavailable.
This answer is only visible to premium members
This answer is only visible to premium members
This answer is only visible to premium members
let msg = 'error'
alert(msg) 
This answer is only visible to premium members
This answer is only visible to premium members

This answer is only visible to premium members

Subscription is currently unavailable.
This answer is only visible to premium members
This answer is only visible to premium members
This answer is only visible to premium members
let msg = 'error'
alert(msg) 
This answer is only visible to premium members
This answer is only visible to premium members

This answer is only visible to premium members

Subscription is currently unavailable.
const { error, log } = require("console");
const { appendFile, readFile } = require("fs");
const { createInterface } = require("readline");

const rl = createInterface({
  input: process.stdin,
  output: process.stdout,
});

function display() {
  readFile("students.txt", "utf8", (err, data) => {
    if (err) {
      error("Error reading file:", err);
    } else {
      log("\nCurrent students:");
      log(data);
    }
    promptUser();
  });
}

function save(name, id) {
  const data = `${name}:${id}\n`;

  appendFile("students.txt", data, (err) => {
    if (err) {
      error("Error saving data:", err);
    } else {
      log(`Saved: ${name} (ID: ${id})`);
      display();
    }
  });
}

function promptUser() {
  rl.question("Enter student name (or 'exit' to quit): ", (name) => {
    if (name.toLowerCase() === "exit") return rl.close();


    rl.question("Enter student ID: ", (id) => {
      save(name, id);
    });
  });
}

appendFile("students.txt", "", (err) => {
  if (err) {
    error("Error creating file:", err);
  } else {
    log("Welcome to the Student Management System");
    promptUser();
  }
});

rl.on("close", () => {
  log("Thank you for using the Student Management System. Goodbye!");
  process.exit(0);
});
while 1:
    name, shomare_daneshjooei = input("nam khod ra vared konid :"), input("shomare daneshjooei ra vared konid :")
    if name == "":
        break
    hasel = f'###\nNam :{name}\nshomare : {shomare_daneshjooei}\n'
    save = open("Etelaat.txt", "a")
    save.write(hasel)
    save.close()

namayesh = open("Etelaat.txt", 'r')
print(namayesh.read())
namayesh.close()
package org.example
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File
import java.lang.reflect.Type

fun main() {
    val map1 = mutableMapOf<String, String>()
    val file = File("D:\\New folder (5)\\students.txt")
    var finish :String

    while (true) {
        try {
            when (menu1()) {
                1 -> {
                    finish=gsonAppend(menu2(map1),file)
                    map1.clear()
                   map1.putAll(toSaved(finish,map1))
                    println("information is saved")
                }
                2 -> {
                    showing(file)
                }
                0 -> {println("Program is Exist")
                    break
                }
            }
        } catch (e: Exception) {
            println(e.message)
        }
    }
}

fun menu1(): Int {
    println("Please Enter one number that is want:")
    println(" Enter:[1]->To register student name and student number")
    println(" Enter:[2]->To show the list of student names along with the student number")
    println(" Enter:[0]->To Exit of Program")
    val number = readlnOrNull()?.toInt()!!
    return number
}

fun menu2(map1:MutableMap<String,String>): Pair<String, String> {
    println("Please Enter Student name")
    val name = readlnOrNull()!!
    println("Please Enter Student number")
    val number: String = readlnOrNull()!!
    return map1.let { (name to number) }
}

fun gsonAppend(map1: Pair<String, String>,file:File):String {
    val gson = Gson()
    val map2 = gson.toJson(map1)
    file.appendText(map2)
    return map2
}

fun toSaved(string1:String,map1:MutableMap<String,String>):MutableMap<String,String>{
    val gson = Gson()
    val mutableMapProduct: Type = object : TypeToken<MutableMap<String,String>>() {}.type
    val result = gson.fromJson<MutableMap<String,String>>(string1,mutableMapProduct )
    map1.clear()
    map1.putAll(result)
    return map1
}

fun showing(file:File){
    file.forEachLine { println(it) }
}
User 848 Download Kotlin
def save_student_info():
    while True:
        # Get information from the user
        name = input("اسم دانشجو را وارد کنید (برای خروج، 'exit' را وارد کنید): ")
        if name.lower() == 'exit':  # Check to exit
            break
        student_id = input("شماره دانشجویی را وارد کنید: ")
        
        # Save information in the file
        with open("students.txt", "a") as file:  # Open the file to add mode
            file.write(f"{name}, {student_id}\n")  # Write information in the file
        
        # Reading and displaying the entire file information
        with open("students.txt", "r") as file:  # Open the file to read mode
            print("\nکل اطلاعات ذخیره شده در فایل:")
            for line in file:
                print(line.strip())  # Display any line without additional distances

# Implementation of the function
save_student_info()
Mma123 Download Python
def add_student_info():
    # Get a student name and number of user
    name = input("نام دانشجو را وارد کنید: ")
    student_id = input("شماره دانشجویی را وارد کنید: ")

    # Open the file as Append and save information
    with open("students.txt", "a") as file:
        file.write(f"{name}, {student_id}\n")

    # Reading and displaying the entire file information
    with open("students.txt", "r") as file:
        content = file.read()
        print("\nمحتویات فایل students.txt:\n")
        print(content)
Milad.bio Download Python
stu_file=open('D:\\student.txt','a')
while 1:
    name=input("Name : ")
    if name=='':break
    password=input("password : ")
    if password=='':break
    stu_file.write(f"name : {name} - password : {password}\n")
stu_file.close()  
stu_file=open('D:\\student.txt','r')
print(stu_file.read())
stu_file.close()
User 448 Download Python
import pickle
import os
class Students:
    def __init__(self,name,student_num):
        self.name=name
        self.student_num=student_num
students=[]
if os.path.exists("students.txt"):
    f=open("students.txt","rb")
    try:
        students=pickle.load(f) 
    except:
        pass
else:
    f=open("students.txt","x")
f.close()
while 1:
    name=input("name: ")
    if(name==""):
        break
    number=input("student number: ")
    s=Students(name,number)
    students.append(s)
print("list of students : ")
f=open("students.txt","ab")
pickle.dump(students,f)
f.close()
for student in students:
   print(f"name: {student.name}, code: {student.student_num}")
Saeeda33 Download Python
<< Previous page 1 2 Next page >>

Submit answer

Submitting answers is currently unavailable.

Related content

Detection using AI
×
×
Close