M01
M01

Reputation: 41

Using a file for reading and writing simultaneously fails

I am trying to write a program that:

  1. creates a file
  2. asks the user for input to put in it (their password)
  3. reads that info and prints it back out.

At the moment reading the file returns nothing. How can I make it work?

This is my code:

f = open ('password.txt', 'a+')
password = input("Enter a password: ")
f.write (str(password))
words = f.read()
print (words)
f.close ()   

Upvotes: 1

Views: 43

Answers (1)

Christian Witts
Christian Witts

Reputation: 11585

The reason why your f.read() gets no data, is because the file pointer will be at the end of the file. You can use .seek(0) to go back to the beginning of the file before you read it in, for eg.

f.write(str(password))
f.seek(0)  # Return to the beginning of the file
words = f.read()
print(words)
f.close()

You can take a look at the Input/Output Tutorial, and doing a find on the page for seek will give you some more information about it.

Upvotes: 2

Related Questions