0

Before I get hate, I haven't found a link which answers my question. I am a beginner at Python 3.

I am supposed to write a function to open a file I wrote (data.txt) which says 'Hi there!' with a newline character that is suppose to give me a count of 10.

The code I have written below gives me the first test case value of 10 but it fails the hidden test case - which is supposed to give me a value of 81. What is wrong with my code?

def file_size(lines):
    """docstring"""
    with open('data.txt', 'r') as file:
        lines = file.read()
        return len(lines)

print(file_size('data.txt'))
# data.txt contains 'Hi there!' followed by a new line character.

ans = file_size('alongertextfile.txt')
print(ans)
khelwood
  • 55,782
  • 14
  • 81
  • 108
Saxasianguy
  • 47
  • 1
  • 1
  • 7
  • 1
    Hard to say what the problem is here, since the test case is hidden. Wild guess: they are including carriage return characters in the 81 test case, which may get ignored during reading depending on your OS. What happens if you open the file with the "rb" mode instead of "r"? – Kevin Oct 16 '15 at 14:05
  • secret test case is ans = file_size('alongertextfile.txt') print(ans) – Saxasianguy Oct 16 '15 at 14:05
  • @Kevin using 'rb' gives me a value of 11 – Saxasianguy Oct 16 '15 at 14:06
  • Are you supposed to return the size in bytes or the number of characters in the file? Remember that unicode characters != bytes. Take a look at this question, to see how to check file size: http://stackoverflow.com/questions/2104080/how-to-check-file-size-in-python – Maciek Oct 16 '15 at 14:07
  • I'm supposed to return the number of characters in the file @Maciek – Saxasianguy Oct 16 '15 at 14:08
  • Do you know what value does your code return for this hidden test case? – Maciek Oct 16 '15 at 14:09
  • It returns 10 instead of 81 – Saxasianguy Oct 16 '15 at 14:10
  • 4
    You are passing a file name to your function (using a misleading variable name `lines`), but ignoring it and opening a file with a hard-coded name. – chepner Oct 16 '15 at 14:13

1 Answers1

8

You need to open the file whose name is passed as an argument:

def file_size(filename):
    """docstring"""
    with open(filename, 'r') as file:
        data = file.read()
        return len(data)
chepner
  • 497,756
  • 71
  • 530
  • 681