4

I need to know the size of the file based on file object

import csv
import os
with open("test.csv", "rb") as infile:
    reader = csv.reader(infile)
    print reader
    filesize(reader)
def filesize(reader):
    os.getsize(reader) #And i need work with reader for more details.so I must need to pass a reader or file object

When I run this I got an output is

<_csv.reader object at 0x7f5644584980>

From this file object how I get the size of the file?

And I checked this site but these are not CSV attribute size of an open file object

EDIT: When I use that two inbuilt function I got errors that are

AttributeError: '_csv.reader' object has no attribute 'seek' AttributeError: '_csv.reader' object has no attribute 'tell'

10
  • @I told that into my question i tested in this site.It is not valid in csv file Commented Apr 7, 2017 at 12:34
  • 1
    Possible duplicate of Size of an open file object Commented Apr 7, 2017 at 12:34
  • 2
    Can't you use the infile variable ? Commented Apr 7, 2017 at 12:35
  • @CristiFati It is not duplicates.Why you said that it is duplicate.Can u prove that Commented Apr 7, 2017 at 12:37
  • @bobmarti Its a duplicate because the best method in your case seems to be the one indicated in the accepted answer. Commented Apr 7, 2017 at 12:38

3 Answers 3

4

Adding this answer because it actually answers the question asked about using the file object directly:

import csv
import os
with open("test.csv", "rb") as infile:
    reader = csv.reader(infile)
    print reader
    infile.seek(0, os.SEEK_END)
    filesize = infile.tell()
Sign up to request clarification or add additional context in comments.

Comments

4

You can use os.path.getsize or os.stat

import os
os.path.getsize('test.csv')

OR

os.stat('test.csv').st_size 

Return the size, in bytes.

Comments

2

What's wrong with os.path.getsize?

With your code:

import os
import csv
with open("test.csv", "rb") as infile:
   reader = csv.reader(infile)
   print os.path.getsize(infile.name)

The size is in bytes.

2 Comments

@duan I need to pass the reader into another function then how i get the solution
@bobmarti, you can't access the file/path from the reader, it design to get an iterable, not a file, you will have to pass the filesize/file object to your other function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.