Priyx
Priyx

Reputation: 73

Issue in writing reverse data from one csv file to another

I want to reverse the columns data keeping column header same of fil1.csv and write them into file2.csv. I am using pandas but this code is only coping the column headers to file2.csv and not the data inside them.

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 data

week num
Mon  675
Tue  6757
Wed  790
Thu  3231
sat  5677

desired file2.csv

week num
sat  5677
Thu  3231
Wed  790
Tue  6757
Mon  675

I also tried below code but this is printing the data as a list and all data in one column only. I don't want that.

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 from this code:

week      num
sat,5677
Thu,3231
Wed,790
Tue,6757
Mon,675

Upvotes: 0

Views: 290

Answers (1)

Jayvee
Jayvee

Reputation: 10875

for reversing you just need this:

df = pd.read_csv("file1.csv", header = 0)
df.iloc[::-1].to_csv("file2.csv", index=False)

Upvotes: 1

Related Questions