1

I want to save the output as a text file on my system. The name of the output file should get from the user in command prompt.

 output = input("Enter a name for output file:") my_file = open('/output.txt', "w") for i in range(1, 10): my_file.write(i) 

Is this correct way of doing??

1
  • Right now you're writing to a file literally named output.txt. If you want to use the user's input as the file name, you'll have to pass something like output + '.txt' to the open function. Commented Sep 28, 2014 at 5:41

4 Answers 4

3

Do like this

output = raw_input("Enter a name for output file:") my_file = open(output + '.txt', "w") for i in range(1, 10): my_file.write(str(i)) 
Sign up to request clarification or add additional context in comments.

1 Comment

It will not work since TypeError will be raised at the write method, you need to write str.
1

You can do the following:

import os # you can use input() if it's python 3 output = raw_input("Enter a name for output file:") with open("{}\{}.txt".format(os.path.dirname(os.path.abspath(__file__)), output), "w") as my_file: for i in range(1, 10): my_file.write("".format(i)) 

At this example we are using the local path by using os.path.dirname(os.path.abspath(__file__)) we will get the current path and we will add it output.txt

  1. To read more about abspath() look here

  2. To read more about with look here

  3. write method in you case will raise a TypeError since i needs to be a string

1 Comment

Down-voter can you explain your down-vote so i can improve the answer?
0

So couple of changes I made. You need to do something like:

 output + '.txt' 

to use the variable output as the file name.

Apart from that, you need to convert the integer i to a string by calling the str() function:

 str(i) 

becuase the write function only takes strings as input.

Here is the code all together:

 output = raw_input("Enter a name for output file: ") my_file = open(output + '.txt', 'wb') for i in range(1, 10): my_file.write(str(i)) my_file.close() 

Hope this helps!

Comments

0

You can do it in one line so you will have your txt file in your .py file path:

 my_file=open('{}.txt'.format(input('enter your name:')),'w') for i in range(1, 10): my_file.write(str(i)) my_file.close() 

Note: if you are using python 2.x use raw_input() instead of input .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.