I know how to do it for a TXT file, but now I am having some trouble doing it for a CSV file.
How can I read a CSV file from the bottom in Python?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Pretty much the same way as for a text file: read the whole thing into a list and then go backwards:
If you want to get fancy, you could write a lot of code that reads blocks starting at the end of the file and working backwards, emitting a line at a time, and then feed that to
csv.reader, but that will only work with a file that can be seeked, i.e. disk files but not standard input.That’s a bit trickier. Luckily, all
csv.readerexpects is an iterator-like object that returns a string (line) per call tonext(). So we grab the technique Darius Bacon presented in “Most efficient way to search the last x lines of a file in python” to read the lines of a file backwards, without having to pull in the whole file:and feed
reversed_linesinto the code to reverse the lines before they get tocsv.reader, removing the need forreversedandlist:There is a more Pythonic solution possible, which doesn’t require a character-by-character reversal of the block in memory (hint: just get a list of indices where there are line ends in the block, reverse it, and use it to slice the block), and uses
chainout ofitertoolsto glue the line clusters from successive blocks together, but that’s left as an exercise for the reader.Aargh! There’s always something. Luckily, it’s not too bad to fix this:
Of course, you’ll need to change the quote character if your CSV dialect doesn’t use
".