[英]Writing data from one CSV file to another CSV file using Python
[英]Issue in writing reverse data from one csv file to another
我想反轉與 fil1.csv 相同的列數據保留列 header 並將它們寫入 file2.csv。 我正在使用 pandas 但此代碼僅將列標題處理為 file2.csv 而不是其中的數據。
df = pd.read_csv("file1.csv", header = 0)
reversed_df = df.iloc[::-1]
file2= csv.writer(open("file2.csv", "w", newline=""), delimiter=",")
file2.writerow(reversed_df)
file1.csv 數據
week num
Mon 675
Tue 6757
Wed 790
Thu 3231
sat 5677
所需文件2.csv
week num
sat 5677
Thu 3231
Wed 790
Tue 6757
Mon 675
我也嘗試了下面的代碼,但這是將數據打印為列表,並且所有數據僅在一列中。 我不想要那個。
with open("fil1.csv") as fr, open("file2.csv","wb") as fw:
cr = csv.reader(fr,delimiter=";")
cw = csv.writer(fw,delimiter=";")
cw.writerow(next(cr)) # write title as-is
cw.writerows(reversed(list(cr)))
output 來自此代碼:
week num
sat,5677
Thu,3231
Wed,790
Tue,6757
Mon,675
為了扭轉你只需要這個:
df = pd.read_csv("file1.csv", header = 0)
df.iloc[::-1].to_csv("file2.csv", index=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.