-1

I got this question:

Write a function file_size(filename) that returns a count of the number of characters (example below) in the file whose name is given as a parameter.

It is suggested that you write your function in a file called filesize.py, and that you save that file in the same directory/folder as any input data files you wish to read before testing your function.

You may assume that when being tested in this CodeRunner question your function will never be called with a non-existent filename.

For example, if data.txt is a file containing just the following: Hi there! , a call to file_size('data.txt') should return the value 10. This includes the newline character that will be added to the line when you're creating the file and hit the ENTER key at the end of the line.

I've written this much so far however it says I have a syntax error in line 1, position 0 and position 19?

def file_size(data.txt):
"""counts number of characters in file"""
with open('data.txt', 'r') as file_size:
    for line in file_size:
        print(len(line))

However, when I remove everything before, it works and shows the correct answer of 10 characters in my data.txt in my folder.

with open('data.txt', 'r') as file_size:
    for line in file_size:
        print(len(line))
3
  • what do you think passing data.txt is doing? Apr 10, 2015 at 9:07
  • Thanks! It's working now. However, its not passing the pylint style checks. It says "************* Module source W: 4,34: Redefining name 'file_size' from outer scope (line 2) (redefined-outer-name) W: 2,14: Unused argument 'filename' (unused-argument)" Apr 10, 2015 at 9:09
  • You need to pass the variable to open and pass the string 'data.txt' to the function when you call the function Apr 10, 2015 at 9:10

3 Answers 3

1

Your variable name cannot contain a dot. Try this instead.

def file_size(filename):
1

I believe the problem is the data.txtparameter name. Python surely doesn't know what to do with it. Try this:

def file_size(filename): 
    """counts number of characters in file""" 
        with open(filename, 'r') as file_size: 
            ...
0

data.txt is not a valid name for a parameter (because of the dot).

Change

def file_size(data.txt):

to

def file_size(filename):

and then use filename as an argument for open().

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.