1

I have some python code that reads and writes to and from a file:

#!/usr/bin/python3.9

# test.py

def setupFile(filename):
    f = open(filename, "w")
    f.write("Writing to file")
    f.close()

def readFileWithVar(filename):
    f = open(filename, "r")
    contents = f.read()
    print(f"readFileWithVar: {contents}")
    assert (contents == "Writing to file")

def readFileInline(filename):
    f = open(filename, "r")
    contents = f.read()
    print(f"readFileInline: {contents}")
    assert(f.read() == "Writing to file")
    f.close()

testFile = "testFile.txt"
setupFile(testFile)
readFileInline(testFile)
readFileWithVar(testFile)

Why does the first function, "readFileInline" fail the assertion with the inline f.read() statement, when I run python test.py?

testFile.txt

Writing to file

EDIT: I fixed a typo in my question earlier, I meant to say the first function, not the second function.

jmd
  • 11
  • 1
  • 2
  • Hey just a note, but you're using `testFile` directly in your functions when I think you want to be using `filename`. – M Z Jan 09 '21 at 05:20
  • 1
    It doesn't look like setFile() is ever called? Does testFile.txt contain any text? – ohthatgeoff Jan 09 '21 at 05:20
  • and note that you don't close the files in your read functions, just out of good practice it might be a nice idea to use `with open() as f:` – M Z Jan 09 '21 at 05:22
  • After the edit: `readFileWithVar` is neither the first function declared nor run? And `setupFile` does not have an `assert`. If you mean the readFileInline function, well, you read twice. You may need `f.seek(0,0)` – M Z Jan 09 '21 at 05:32
  • 1
    Because **you already read from the file**. So when you `f.read()` from it again in your assertion, the cursor is at the end of the file, and an empty string is returned. Have you read the documentation? If you remove `contents = f.read()` it would work – juanpa.arrivillaga Jan 09 '21 at 05:34
  • Oh whoops, nevermind I understand now. I was calling f.read() twice to initialize contents and check the assertion. – jmd Jan 09 '21 at 05:38

0 Answers0