Find the last row from a CSV input Python
You can get the last element in an array like so:
some_list[-1]
In fact, you can do much more with this syntax. The some_list[-n]
syntax gets the nth-to-last element. So some_list[-1]
gets the last element, some_list[-2]
gets the second to last, etc
So in your case, it would be:
import csv
def import_csv(csvfilename):
data = []
with open(csvfilename, "r", encoding="utf-8", errors="ignore") as scraped:
reader = csv.reader(scraped, delimiter=',')
for row in reader:
if row: # avoid blank lines
row_index += 1
columns = [str(row_index), row[0], row[1], row[2]]
data.append(columns)
return data
data = import_csv(file_name)
last_row = data[-1]
Reading the last row or the row having the latest value in csv file
The csv reader is a generator, you can convert that to a list. You can get the last data in the last line with the following code sample:
import csv
with open('test.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=' ')
print(list(csv_reader)[-1][-1])
Get last row in last column from a csv file using python
You can do this: if you want the very last row
with open('data.csv', 'r') as csv:
data = [[x.strip() for x in line.strip().split(',')] for line in csv.readlines()][-1][-1]
print(data)
or if you want all the last elements in each row
with open('data.csv', 'r') as csv:
data = [line.strip().split(',')[-1] for line in csv.readlines()]
print(data)
Python csv read and write, (write only saves last row)
write function overwrites, when you open without "a" option. Do something like this,
f = io.open(filename, "a", encoding="utf-8") # not "w"
How to get the first value of last row of a CSV file using python
if you want to use python only :
with open('csv_file.csv','r') as f:
opened_file = f.readlines()
var = opened_file[-1].split(',')[0]
Get Values from last Row of .csv File
I think you're on a Unix-y system so something simple like this should work + it's fast because it doesn't read the whole file:
import subprocess
last_line = subprocess.check_output(["tail", "-1", "DataLogging.csv"])
# to get the values (parsing via the csv module seems excessive for one line)
temp_hum = [float(x) for x in last_line.split()[2:]]
A cross-platform solution using seek()
could be made by implemeting tail
s approach. A comment in tail
's source code explains how it works:
Print the last N_LINES lines from the end of file FD. Go backward
through the file, reading 'BUFSIZ' bytes at a time (except probably
the first), until we hit the start of the file or have read NUMBER
newlines. START_POS is the starting position of the read pointer
for the file associated with FD (may be nonzero). END_POS is the
file offset of EOF (one larger than offset of last byte). Return
true if successful.
How to access the second to last row of a csv file using python Pandas?
As simple as that :
df1.iloc[-2,:]
Get last row of CSV file and append it onto the end of the same CSV file
Answering my own question:
I have figured out how to maintain the order of columns and append to the end of the existing dataframe. It is worth noting that pd.tail()
does not maintain the order of columns.
df = pd.read_csv('file.csv')
df_fluxes = df.iloc[[-1] * n]
df_fluxes.to_csv(run_dir+'em_line_fluxes.csv', mode='a', header=False, index=False)
Related Topics
Python: Pickle.Load() Raising Eoferror
Python: How to Calculate the Sum of Numbers from a File
How to Iterate Through Cur.Fetchall() in Python
Python-Compare Two String Columns in Same Dataframe, Return Matching Result
What Is the Most Efficient Way to Sum a Dict With Multiple Keys by One Key
Python Not Working in the Command Line of Git Bash
Iterating Over Every Two Elements in a List
Formal and Actual Parameters in a Function in Python
Pandas - Drop Last Column of Dataframe
Conversion of String to Upper Case Without Inbuilt Methods
Discord.Py Show Who Invited a User
Dice Rolling Simulator in Python
Find the Longest Substring in Alphabetical Order
How to Merge Json Objects Containing Arrays Using Python
How to Strip Comma in Python String