如何在CSV文件已存在时填写数据?

huangapple go评论142阅读模式
英文:

How to fill in data on CSV file if it already exisits?

问题

I am trying to write a code that will allow for a user to input a code, once the code has been entered, the code will search for user on a csv file, if the user matches an existing entry on the csv file then it looks for the next available column in the users row and enters the number there. If there is no open slot then it will overwrite the first slot.

如上所示,如果用户 silverspoon 输入代码 8,则应更新 CODE3 列,因为它为空。如果 goldspoon 输入代码 17,则应更新 CODE1 列,因为所有列都有数据。如果 bronzespoon 输入代码 99,则应创建一个新的数据行,因为他们不在列表中。应该如下所示。

这是我目前拥有的代码,但不幸的是,我让用户一次又一次地输入他们的所有代码,并且每次输入新代码时都会更新整行。

now = datetime.now()
entrydate = now.strftime("%m/%d/%Y")
fields = ["USER", "DATE", "CODE1", "CODE2", "CODE3", "CODE4", "CODE5"]
df = pd.read_csv("C:\test\codes.csv")
if username in df.values: # I use this to determine if the user is already on the CSV file
    with open("C:\test\codes.csv", "r") as csvfile, tempfile:
        reader = csv.DictReader(csvfile, fieldnames=fields)
        writer = csv.DictWriter(tempfile, lineterminator='\n', fieldnames=fields)
        for row in reader:
            if row["USER"] == username:
                new_codes = [entrydate, code1, code2, code3, code4, code5]
                row["DATE"], row["CODE1"], row["CODE2"], row["CODE3"], row["CODE4"], row["CODE5"] = new_codes
            row = {
                "USER": row["USER"],
                "DATE": row["DATE"],
                "KEYWORD1": row["CODE1"],
                "KEYWORD2": row["CODE2"],
                "KEYWORD1": row["CODE3"],
                "KEYWORD2": row["CODE4"],
                "KEYWORD3": row["CODE5"],
            }
            writer.writerow(row)
    shutil.move(tempfile.name, "C:\test\codes.csv")
    print(f"{username} updated their code list of {code1}, {code2}, {code3}, {code4}, & {code5} effective {entrydate}")
    return
else:
    with open("C:\test\codes.csv", "a", newline="") as f:
        writer = csv.writer(f)
        writer.writerow([username, entrydate, code1, code2, code3, code4, code5])
        print(f"{username} added {code1}, {code2}, {code3}, {code4}, & {code5} to their code list effective {entrydate}")
        return
英文:

I am trying to write a code that will allow for a user to input a code, once the code has been entered, the code will search for user on a csv file, if the user matches an existing entry on the csv file then it looks for the next available column in the users row and enters the number there. If there is no open slot then it will overwrite the first slot.

如何在CSV文件已存在时填写数据?

As you can see above, if user silverspoon enters a code of 8, then it should update the CODE3 column as it is empty. if goldspoon enters a code of 17, then it should update the CODE1 column since all columns have data. If bronzespoon enters a code of 99, then it should create a new row of data since they are not on the list. It should look like below.

如何在CSV文件已存在时填写数据?

This is a code I currently have but unfortunately I am making user enter all their codes all over again and it would updates the whole row every time new codes are entered.

    now = datetime.now()
    entrydate = now.strftime("%m/%d/%Y")
    fields = ["USER", "DATE", "CODE1", "CODE2", "CODE3", "CODE4", "CODE5"]
    df = pd.read_csv("C:\test\codes.csv")
    if username in df.values: # I use this to determine if the user is already on the CSV file
        with open("C:\test\codes.csv", "r") as csvfile, tempfile:
            reader = csv.DictReader(csvfile, fieldnames=fields)
            writer = csv.DictWriter(tempfile, lineterminator='\n', fieldnames=fields)
            for row in reader:
                if row["USER"] == username:
                    new_codes = [entrydate,code1, code2, code3, code4, code5]
                    row["DATE"], row["CODE1"], row["CODE2"], row["CODE3"], row["CODE4"], row["CODE5"] = new_codes
                row = {
                    "USER": row["USER"],
                    "DATE": row["DATE"],
                    "KEYWORD1": row["CODE1"],
                    "KEYWORD2": row["CODE2"],
                    "KEYWORD1": row["CODE3"],
                    "KEYWORD2": row["CODE4"],
                    "KEYWORD3": row["CODE5"],
                }
                writer.writerow(row)
        shutil.move(tempfile.name, "C:\test\codes.csv")
        print(f"{username} updated their code list of {code1} , {code2} , {code3} , {code4} , & {code5} effective {entrydate}")
        return
    else:
        with open("C:\test\codes.csv","a", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([username,entrydate,code1,code2,code3,code4,code5])
            print(f"{username} added {code1} ,{code2} ,{code3} , {code4} , & {code5} to to their code list effective {entrydate}")
            return                

答案1

得分: 1

以下是您提供的代码的中文翻译部分:

# 导入所需的库
import csv
import pandas as pd
import shutil
import os
from datetime import datetime

# 获取当前日期
now = datetime.now()
entrydate = now.strftime("%m/%d/%Y")

# 定义字段名称
fields = ["用户", "日期", "代码1", "代码2", "代码3", "代码4", "代码5"]

# 文件路径
filename = "C:\\test\\codes.csv"
temp_filename = "C:\\test\\temp_codes.csv"

# 用户名和新代码
username = "silverspoon"
new_code = 8

# 读取CSV文件
df = pd.read_csv(filename)

# 检查用户名是否在数据中
if username in df.values:
    # 打开原始文件和临时文件
    with open(filename, "r") as csvfile, open(temp_filename, "w", newline="") as tempfile:
        reader = csv.DictReader(csvfile, fieldnames=fields)
        writer = csv.DictWriter(tempfile, lineterminator='\n', fieldnames=fields)
        writer.writeheader()

        # 遍历文件中的每一行
        for row in reader:
            if row["用户"] == username:
                for i in range(1, 6):
                    code_key = f"代码{i}"
                    if not row[code_key]:
                        row[code_key] = new_code
                        break
                else:
                    row["代码1"] = new_code
                row["日期"] = entrydate
            writer.writerow(row)

    # 移动临时文件到原始文件位置
    shutil.move(temp_filename, filename)
    print(f"{username} 更新了他们的代码列表,生效日期为 {entrydate}")
else:
    # 如果用户不存在,则追加新行
    with open(filename, "a", newline="") as f:
        writer = csv.writer(f)
        writer.writerow([username, entrydate, new_code, "", "", "", ""])
        print(f"{username} 添加了新代码,生效日期为 {entrydate}")

请注意,我已经翻译了代码的主要部分,如变量名、注释和字符串。如果您需要进一步的帮助或有其他问题,请随时提问。

英文:

There is some error in your code, I modified it according to the rules you want ( when the user exist and no empty slot, when there is no empty slot and if the user dont exist ) dont forget to replace username and new_code with the user input.

import csv
import pandas as pd
import shutil
import os
from datetime import datetime
now = datetime.now()
entrydate = now.strftime("%m/%d/%Y")
fields = ["USER", "DATE", "CODE1", "CODE2", "CODE3", "CODE4", "CODE5"]
filename = "C:\\test\\codes.csv"
temp_filename = "C:\\test\\temp_codes.csv"
username = "silverspoon"
new_code = 8
df = pd.read_csv(filename)
if username in df.values:
with open(filename, "r") as csvfile, open(temp_filename, "w", newline="") as tempfile:
reader = csv.DictReader(csvfile, fieldnames=fields)
writer = csv.DictWriter(tempfile, lineterminator='\n', fieldnames=fields)
writer.writeheader()
for row in reader:
if row["USER"] == username:
for i in range(1, 6):
code_key = f"CODE{i}"
if not row[code_key]:
row[code_key] = new_code
break
else:
row["CODE1"] = new_code
row["DATE"] = entrydate
writer.writerow(row)
shutil.move(temp_filename, filename)
print(f"{username} updated their code list with {new_code} effective {entrydate}")
else:
with open(filename, "a", newline="") as f:
writer = csv.writer(f)
writer.writerow([username, entrydate, new_code, "", "", "", ""])
print(f"{username} added {new_code} to their code list effective {entrydate}")

huangapple
  • 本文由 发表于 2023年4月17日 01:18:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76029261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定