1

First, code gets a name and makes a file with w permission (also tested r+) and it should write any other input in file, but it doesn't. I get an empty file.

user_name_in =input("gets Input")
fname = user_name_in
f = input()
ufile = open(fname,"w")
while True:
    f=input(answer)
    ufile.write(f)
6
  • 2
    Have you tried with open(fname, 'w') as ufile: ufile.write(f) ? Commented Aug 22, 2016 at 12:16
  • 3
    Add ufile.close() and see if that fixes it. Commented Aug 22, 2016 at 12:16
  • 3
    @Rawing you would still have to flush the file. always use the with to handle files. Commented Aug 22, 2016 at 12:17
  • @Rawing Tested , still no content in result file Commented Aug 22, 2016 at 12:19
  • @MohammadHoseinBin Did you add it at the very end outside the loop? Also, have something that terminates the loop so it can reach the end Commented Aug 22, 2016 at 12:19

2 Answers 2

5

As i wrote in the comments, always use the with block to handle files as it takes care of intricacies you don't have to worry about. Now on the code, you repeat yourself, for example the first two lines are actually one.. This is what it would look when cleaned a bit.

fname = input("gets Input")
with open(fname, "w") as ufile:
    f = input('write something')
    ufile.write(f)

And as others also noticed, the answer is never declared, there is no termination condition and the input prompts are either not the best or totally absent.

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

1 Comment

Answer is declared somewhere else , I declared it externally in String management part of program.
1

This code works for me:

user_name_in =input("gets Input")
fname = user_name_in
f = input()
ufile = open(fname,"w")
while True:
    f=input(answer)
    ufile.write(f)

Some considerations: I don't see where answer is declared, neither python interpreter see :P, maybe you forgot to paste this part of the code or indeed this was the error?

I don't understand why you assign the name of the file to a variable and then re-assign to another one.

How do I stop writing to the file? The only way I found was Ctrl-C, which doesn't sound ideal.

To reassure the file is being closed you can replace it with a with open(fname) as ufile block

1 Comment

f variable got same use and in optimized final code will be fixed. there are if's in while that'll break the loop. i just placed only necessary parts of Code

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.