我如何在Python中写入CSV,并在最后一行下面有新数据?



我有一个CSV文件与我所有的乙烯基,我正在编写一个程序来打开CSV文件,然后问用户一个新的LP的详细信息,然后程序应该写入数据到CSV文件。正在发生的事情是,数据被写入CSV文件中最后一条记录的右侧,而不是作为最后一行下面的新行。这是我的代码:

from csv import writer
def append_list_as_row(file_name, list_of_elem):
with open("MusicDatacopy.csv", 'a+', newline='') as write_obj:

csv_writer = writer(write_obj)
csv_writer.writerow(list_of_elem)
artist = input("Enter Artist name: ").title()
album = input("Enter Album name: ").title()
month = input("Enter month bought: ").title()
owner = input("Enter Name of Owner: ").title()
f_name = input("Enter artist f_name: ").title()
s_name = input("Enter artist f_name: ").title()
genre = input("Enter genre: ").title()
row_contents = [artist, album, month, owner, f_name, s_name, genre]
append_list_as_row('MusicDatacopy.csv', row_contents)

是否有一种方法可以强制CSV编写器将新数据写在最后一行数据下面,然后根据艺术家(s_name)的姓氏对CSV文件进行排序?

提示您说您想让CSV保持排序状态。要做到这一点,首先需要读入整个文件。添加您的新信息,根据姓氏(然后可能是名字)进行排序。最后把整个东西写回来。

我假设你的文件有一个头。在这种情况下,您需要注意不要将其作为排序的一部分。

例如:

import csv
def append_list_as_row(file_name, row):
filename = "MusicDatacopy.csv"
# Read the existing file in
with open(filename, newline='') as f_input:
csv_reader = csv.reader(f_input)
header = next(csv_reader)
data = list(csv_reader)

data.append(row)    # add the new row to the end
data.sort(key=lambda x: (x[5], x[4]))    # sort the data based on s_name
# Write the whole file back
with open(filename, 'w', newline='') as f_output:
csv_writer = csv.writer(f_output)
csv_writer.writerow(header)
csv_writer.writerows(data)

artist = input("Enter Artist name: ").title()
album = input("Enter Album name: ").title()
month = input("Enter month bought: ").title()
owner = input("Enter Name of Owner: ").title()
f_name = input("Enter artist f_name: ").title()
s_name = input("Enter artist s_name: ").title()
genre = input("Enter genre: ").title()
row_contents = [artist, album, month, owner, f_name, s_name, genre]
append_list_as_row('MusicDatacopy.csv', row_contents)

试试这个:

import pandas as pd
df = pd.read_csv("MusicDatacopy.csv")
artist = input("Enter Artist name: ").title()
album = input("Enter Album name: ").title()
month = input("Enter month bought: ").title()
owner = input("Enter Name of Owner: ").title()
f_name = input("Enter artist f_name: ").title()
s_name = input("Enter artist s_name: ").title()
genre = input("Enter genre: ").title()
columns = df.columns
df2 = pd.DataFrame([[artist, album, month, owner, owner, f_name, s_name, genre]], columns=columns)
df.append(df2, ignore_index=True)
df.sort_values(["s_name", "f_name"], inplace=True)
df.to_csv('MusicDatacopy.csv', index=False)

p。我还没有测试过,如果遇到问题请告诉我。注:请确保以与csv

中的列相同的顺序创建列表。

相关内容

  • 没有找到相关文章

最新更新