2

I put a number into a file, but the next time I opened it with the Open() command, I put the number inside it, which was string, into a variable int() but the number was gone!!!

file = open('times.txt', 'r')  # wrong = 4
print(file.read())  # wrong = 4
wrong = list(file.read())  # there is a problem, when is str not problem but if int => wrong = 0
print(wrong)  # wrong = 0

1 Answer 1

3

Once you call read() on file for the first time the cursor is set to the end of the file.

Should you want to read the contents of file again you can use seek:

file.seek(0)

Which will return you to the beginning of the file.

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

1 Comment

It may be worth mentioning that saving the output in a variable is probably best if they plan on reading the content multiple times anyway (unless they expect the file to be huge).

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.