Hello How i could make Python Write and Read at the sametime using (with) i did this simple function to add names in txt file but the output is usully empty…
def student():
with open("students.txt","w+") as my_file:
for i in range(20):
user = input("Enter your name : ")
my_file.write(f"{user}\n")
print(my_file.read())
student()
tried r+ w+ a+ but none of them were working only r works but then i can’t add to the file
>Solution :
You need to reposition the cursor to the start of the file, write moves it to the end:
def student():
with open("students.txt", "w+") as my_file:
for i in range(20):
user = input("Enter your name : ")
my_file.write(f"{user}\n")
my_file.seek(0) # reposition cursor to start of file
print(my_file.read())
student()