Python Forum

Full Version: csv file saving problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import csv


def save_users_csv(new):
    locals()
    users_file = open(r'C:\Users\patri\PycharmProjects\air_traffic_control_system\users.csv', "r+", newline='')
    writer = csv.writer(users_file)
    writer.writerows(new)
    print(new)      # test only
    users_file.close()


def read_user_csv():
    global user
    user_file = open(r'C:\Users\patri\PycharmProjects\air_traffic_control_system\users.csv', "r+", newline='')
    reader = csv.reader(user_file)
    user = list(reader)
    user_file.close()
    return user


read_user_csv()
input_user = input("User: ")
for x in range(len(user)):
    if input_user == user[x][0]:
        target = x
        del user[target]
        print("Now you are deleting user ")
save_users_csv(user)
I am trying to delete a user in the CSV file in python. I have tested many about the variables and the list (user) before and after delete function, everything run properly, the user list has been updated too.
However, the CSV file seems not to be updated. Do I have some mistake? Please help! Appreciate.
when using r+ (read, write) mode, you need to control the stream position before reading or writing
see, seek, tell and flush: https://docs.python.org/3/library/io.htm...OBase.tell

seek has three modes, there are builtin constants for the values, which are:
SEEK_SET - value 0 Sets stream pointer to beginning of file.
SEEK_CUR - value 1 Sets stream pointer to current position
SEEK_END - value 2 Sets stream pointer to end of file.

tell will return the current stream position (relative to BOF)

flush will flush remaining data in buffer to file this step is needed for premature file close, and is a safe bet if unshure.
To avoid all of this, I would just open in the function save_users_csv as 'w' rather than r+ as you are overwriting the entire file anyway.