Python Forum
reading and writing to a text file help - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: reading and writing to a text file help (/thread-4609.html)



reading and writing to a text file help - jobemorgan - Aug-29-2017

I am trying to create a program where the code asks questions and puts it into a text file. Is there any errors here or am I missing something out
f = open("test.txt","r+")
print (f.write("hello"))
print (f.read())



RE: reading and writing to a text file help - metulburr - Aug-29-2017

read the files tutorial for more info
https://python-forum.io/Thread-Basic-Files

res = input('question')

with open('filename.txt','w') as f:
    f.write(res)



RE: reading and writing to a text file help - Myersj281 - Aug-30-2017

try this:
print("ask your question? ", end="") #end="" is optional and removes the new line character so that input can be on the same line as the question
answer = input()
#write to file
with open("your file", "a") as variable_name: #a is append mode so new lines are automatic
 print(answer, file=variable_name)
[/python

[python]
#read from file and print text to screen
with open("your file", "r") as variable_name: #r is read only mode
 for line in variable_name:
  print(line)



RE: reading and writing to a text file help - nilamo - Sep-11-2017

(Aug-29-2017, 08:40 PM)jobemorgan Wrote: I am trying to create a program where the code asks questions and puts it into a text file. Is there any errors here or am I missing something out
f = open("test.txt","r+")
print (f.write("hello"))
print (f.read())

Yes.
1) You don't close the file.  Other people have been suggesting the with block, because it'll handle closing resources automatically.
2) You never ask questions.
3) You never get the responses to the questions you never ask :p
4) You ignore the responses you never get, and instead always write "hello".
5) You're reading and writing from the same file, without seek()ing.  I'm not actually sure what print(f.read()) does here, since you're already at the end of the file.


RE: reading and writing to a text file help - Sagar - Sep-12-2017

try this:
f = open("test.txt","r+")
print (f.write("hello"))
f.seek(0,0)
print (f.read())
f.close()