csv 如何使文件更改从下一个单元格开始

ecfsfe2w  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(91)

看,我有一个文件,标题在第一行:**[“Date of creation”,“ID”,“Note”]**我有一个函数,它可以更改特定的行,但更改是从第一个点开始,也就是从日期开始。必须将日期更改为当前日期,而不是手动更改

def editNote(path):
    myList = []
    print("Please enter the new details for each of the following: ")
    # Create an empty array, write all the data from the file there
    with open(path, 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            myList.append(row)
        file.close()

    # We display all notes by numbering, the user enters the number of the desired line
    print("Please see the details to editing: ")
    for i in range(len(myList)):
        print("Row" + str(i) + " :" + str(myList[i]))

    userInputToEdit = int(input("Which row would you like to change? Enter 1 - " + str(len(myList) - 1) + ": "))

    # Changing data on a specific line
    for i in range(len(myList[0])):
        newDetails = input("Enter new data for " + str(myList[0][i + 1]) + ": ")
        myList[userInputToEdit][i] = newDetails

    # Show modified ARRAY
    print("Please see the details of the new file below: ")
    for i in range(len(myList)):
        print("Row" + str(i) + " :" + str(myList[i]))

    # If yes, then we make changes already in the file
    changeCSV = input("Would you like to make the changes to the csv file? Y/N: ").lower()
    if changeCSV == "y":
        with open(path, 'w+', newline='') as file:
            writer = csv.writer(file)
            for i in range(len(myList)):
                writer.writerow(myList[i])
            file.close()

我试图将i变量增加1,但最终得到 list index out of range 错误

ltqd579y

ltqd579y1#

python range函数可以接受两个参数range(start, end),其中第一个参数是start,所以只需要从1开始而不是0。

# Changing data on a specific line
    myList[userInputToEdit][0] = datetime.now()  # set date first
    for i in range(1, len(myList[0])):
        newDetails = input("Enter new data for " + str(myList[0][i]) + ": ")
        myList[userInputToEdit][i] = newDetails
b1payxdu

b1payxdu2#

要将日期更改为当前日期,您可以执行以下操作:
更改此:

# Changing data on a specific line
for i in range(len(myList[0])):
    newDetails = input("Enter new data for " + str(myList[0][i + 1]) + ": ")
    myList[userInputToEdit][i] = newDetails

这是:

import datetime
    myList[0]['Date of creation'] = datetime.date.today()
    for i in range(1, len(myList[0])):
    newDetails = input("Enter new data for " + str(myList[0][i]) + ": ")
    myList[userInputToEdit][i] = newDetails

重要注意事项包括:
请记住,每一行都是一个dict,因此您可以通过名称而不是索引来访问它。
你可以在一开始import datetime

相关问题