Python CSV 处理:添加新用户时现有用户未保留在输出文件中

问题描述 投票:0回答:1

使用 Python 脚本将新用户添加到 CSV 文件时,之前添加的用户不会保留在输出文件中。该脚本从输出 CSV 文件读取现有用户,从输入 CSV 文件处理新用户,并将现有用户和新用户写入输出 CSV 文件。但是,只有新用户才会写入输出文件,现有用户不会保留。下面是我的代码片段。

import csv
import secrets
import subprocess
from pathlib import Path

# Sets the path to the data directory
data_dir = Path("/home/shayan/Desktop/Python Script/Script_1/data")

# Reading the existing users from the output file
existing_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 file
with 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.")

脚本应在输出文件中保留现有用户,同时从输入文件添加新用户。

python csv automation
1个回答
0
投票

确保现有用户保留在输出 CSV 文件中,同时从输入文件添加新用户。您处理现有用户写入输出文件的方式不正确。

问候

© www.soinside.com 2019 - 2024. All rights reserved.