Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 22217

Python CSV Processing: Existing Users Not Retained in Output File When Adding New Users

$
0
0

When adding new users to a CSV file using a Python script, the previously added users are not retained in the output file. The script reads existing users from an output CSV file, processes new users from an input CSV file, and writes both existing and new users to the output CSV file. However, only the new users are being written to the output file, and the existing users are not retained. Below is the snippet of my code.

import csvimport secretsimport subprocessfrom pathlib import Path# Sets the path to the data directorydata_dir = Path("/home/shayan/Desktop/Python Script/Script_1/data")# Reading the existing users from the output fileexisting_users = set()try:    with open(data_dir / "users_out.csv", "r") as file_output:        reader = csv.DictReader(file_output)        for user in reader:            existing_users.add(user["username"])except FileNotFoundError:    pass  # Ignores if the file does not exist yet# Reading the input file and creating output filewith open(data_dir / "users_in.csv", "r") as file_input, open(data_dir / "users_out.csv", "a") as file_output:    fieldnames = ["username", "password", "real_name"]    writer = csv.DictWriter(file_output, fieldnames=fieldnames)    # Processes new users from the input file    reader = csv.DictReader(file_input)    for user in reader:        if "username" in user and user["username"] not in existing_users:            # Generating a random 16-character password            user["password"] = secrets.token_hex(8)            # Runing useradd command to create user account            useradd_cmd = ["/sbin/useradd","-c", user["real_name"],"-m","-G", "users","-p", user["password"],                           user["username"]]            try:                subprocess.run(useradd_cmd, check=True)            except subprocess.CalledProcessError as e:                # If User already exists, print a message and continue to the next user                print(f"User '{user['username']}' already exists. Skipping...")                continue            # Writing the new user record with password to output file            writer.writerow(user)    print("Finished processing users.")

The script should retain existing users in the output file while adding new users from the input file.


Viewing all articles
Browse latest Browse all 22217

Latest Images

Trending Articles



Latest Images