[英]CSV files - How do I replace a row of data through user input?
我制作了一个 CSV 文件,其中存储了一本书、作者和出版年份。 然后,我在程序将文件数据作为列表显示给用户的地方进行了设置。 我现在想要求用户将 select 一行替换为不同的数据集。 然后我想把这个数据恢复到原来的 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)
将文件作为列表读取。 然后修改该列表。 然后将该列表写回磁盘。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.