Murtaza Kapadia
Murtaza Kapadia

Reputation: 1

Content of file not printing

I am a beginner, learning programming using python 3.7. I am running a basic program to read content of a file after writing on it. But the print function won't print out the content of the file on the terminal. Can you please correct what mistake I am making here:

spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
x = work.read()
print(x)


work.close()

Upvotes: 0

Views: 796

Answers (2)

shifloni
shifloni

Reputation: 719

After the write() completes, the file's object index needs to be moved to the beginning of the file

add work.seek(0) before the read() operation

spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
work.seek(0)
x = work.read()
print(x)


work.close()

Upvotes: 2

JanTinbergen
JanTinbergen

Reputation: 60

You can't actually read your spam variable since it is not a file. Instead:

work = open("NewFile.txt", "w")
work.write(spam)
work.close()

Upvotes: -1

Related Questions