how do i select last raw in CSV files and import in to Excel?

Viewed 33

How i can select last raw in text files with for? this my first idea code :

import glob
import pandas as pd
path = input("Insert location:")
file_list = glob.glob(path + "/*.txt")
txt_list = []
for file in file_list:
    txt_list.append(pd.read_csv(file))
    for file in file_list:
        txt_list[-7::3]
excl_merged = pd.concat(txt_list, ignore_index=True)
excl_merged.to_excel('Total.xlsx', index=False) ]
1 Answers

Your code is incorrect. Here is a version that should work:

import glob
import pandas as pd
path = input("Insert location:")
file_list = glob.glob(path + "/*.txt")
df_list = []
for file in file_list:
    df = pd.read_csv(file)
    df_list.append(df.tail(3)) # last 3 rows from each file dataframe
excl_merged = pd.concat(df_list, ignore_index=True)
excl_merged.to_excel('Total.xlsx', index=False)

Explaination: tail() method takes the last several rows (provided as an argument) from a dataframe.

Related