CSV 文件 - 如何通过用户输入替换一行数据?

时间:2020-12-20 18:22:44

标签: python python-3.x

我制作了一个 CSV 文件,其中存储了一本书、其作者和出版年份。然后我将它设置为程序将文件数据作为列表显示给用户的位置。我现在想要求用户选择一行并将其替换为一组不同的数据。然后我希望这些数据返回到原始 CSV 文件,用修改后的数据覆盖现有数据。我该怎么做?

这是我目前的代码:

import csv

with open("Books.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["", "Book", "Author", "Year released"])

    writer.writerow([0, "To kill a Mockingbird", "Harper Lee", "1960"])
    writer.writerow([1, "A Brief History of Time", "Stephan Hawking", "1988"])
    writer.writerow([2, "The Great Gatsby", "F.Scott Fitzgerald", "1922"])
    writer.writerow([3, "The Man Who Mistook His Wife For a Hat", "Oliver Sacks", "1985"])
    writer.writerow([4, "Pride and Prejudice", "Jane Austen", "1813"])

books = []

with open("books.csv", "r", newline="") as file2:
    reader = csv.reader(file2)
    for row in reader:
        count, book, author, year_released = row
        print(row)

1 个答案:

答案 0 :(得分:0)

以列表形式读入文件。然后修改该列表。然后将该列表写回磁盘。

import csv

with open("Books.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["", "Book", "Author", "Year released"])

    writer.writerow([0, "To kill a Mockingbird", "Harper Lee", "1960"])
    writer.writerow([1, "A Brief History of Time", "Stephan Hawking", "1988"])
    writer.writerow([2, "The Great Gatsby", "F.Scott Fitzgerald", "1922"])
    writer.writerow([3, "The Man Who Mistook His Wife For a Hat", "Oliver Sacks", "1985"])
    writer.writerow([4, "Pride and Prejudice", "Jane Austen", "1813"])

books = []

with open("books.csv", "r", newline="") as file2:
    reader = csv.reader(file2)
    books = list(reader)

print(*books, sep='\n')

line = input("select line: ")
title = input("title: ")
author = input("author: ")
year = input("year: ")

books[int(line) + 1] = [line, title, author, year]

with open("Books.csv", 'w', newline="") as file3:
    writer = csv.writer(file3)
    writer.writerows(books)

print(*books, sep='\n')