1

I am unable to read the data from file in python . Below is the sample code and Error which I am getting .

abc.txt has the value 2015-05-07

f = open("/opt/test/abc.txt","r")
f.read()
last_Exe_date = f.read()
f.close()

while reading the file(anc.txt) i am getting the error : TypeError: argument 1 must be string or read-only character buffer, not file . i am not able to read the value into last_Exe_date from file(abc.txt) . could you please correct me if I am wrong with the code.

3
  • 2
    You're reading the file twice. Try removing the first f.read(). Commented Jul 6, 2015 at 11:37
  • Please show the exact stacktrace of the error message. Currently it is not possible to pinpoint the source (line) of the error message. Commented Jul 6, 2015 at 11:38
  • 2
    Also why are you using semi colons? Commented Jul 6, 2015 at 11:40

2 Answers 2

4

When you read a file once, the cursor is at the end of the file and you won't get anything more by re-reading it. Read through the docs to understand it more. And use readline to read a file line by line.

Oh, and remove the semicolon at the end of your read calls...

Sign up to request clarification or add additional context in comments.

Comments

0

The following should work fine:

f = open("/opt/test/abc.txt","r")
last_Exe_date = f.read()
f.close()

As was said, you had f.read() twice, so when you tried to store the contents into last_Exe_date, it would be empty.

You could also consider using the following method:

with open("/opt/test/abc.txt","r") as f:
    last_Exe_date = f.read()

This will ensure that the file is automatically closed afterwards.

Comments

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.