does not print into the original file
Question:
in the last 2 lines the file1 stays blanks even with the write function. the rest of the code works flawlessly
def modQuantity(filepath: str,):
model = input("Model: ")
size = input("size")
newquantity = input("New Quantity: ")
file = open(filepath, 'r')
tempfile = open(filepath+"temp", 'w')
for line in file:
sep = line.split()
if sep[0] == model and sep[1] == size:
tempfile.write(f"{sep[0]} {sep[1]} {newquantity}n")
else:
tempfile.write(f"{line}")
tempfile.close()
file.close()
tempfile1 = open(filepath+"temp", 'r')
file1 = open(filepath, 'w')
for line1 in tempfile1:
file1.write(f"{line1}")
Answers:
You didn’t close the file so it hadn’t chance to flush the content. You can use that method by yourself or close the file.
I recommend to use contextmanager
so you can be sure file is flushed and closed:
with open(filepath, 'w') as file1:
for line1 in tempfile1:
file1.write(f"{line1}")
in the last 2 lines the file1 stays blanks even with the write function. the rest of the code works flawlessly
def modQuantity(filepath: str,):
model = input("Model: ")
size = input("size")
newquantity = input("New Quantity: ")
file = open(filepath, 'r')
tempfile = open(filepath+"temp", 'w')
for line in file:
sep = line.split()
if sep[0] == model and sep[1] == size:
tempfile.write(f"{sep[0]} {sep[1]} {newquantity}n")
else:
tempfile.write(f"{line}")
tempfile.close()
file.close()
tempfile1 = open(filepath+"temp", 'r')
file1 = open(filepath, 'w')
for line1 in tempfile1:
file1.write(f"{line1}")
You didn’t close the file so it hadn’t chance to flush the content. You can use that method by yourself or close the file.
I recommend to use contextmanager
so you can be sure file is flushed and closed:
with open(filepath, 'w') as file1:
for line1 in tempfile1:
file1.write(f"{line1}")