2

I have code that manipulates data of a file that I currently have hard-coded in the script. I want to be able to prompt the user to chose the input file rather than having to hard-code it. Here is what I have for input. Instead of always using myfile.txt, I'd like the user to be able to choose the file:

with open('myfile.txt', 'rU') as input_file: 
2
  • Use raw_input (Python 2) or input (Python 3) to read the file name and then use that in open Commented May 27, 2016 at 16:26
  • 1
    Choose it how? Through a file picker (see Tkinter)? The command line (consider sys.argv)? Commented May 27, 2016 at 16:28

1 Answer 1

5

Use the input function on Python 3, or raw_input if you're using Python 2:

# Python 3 with open(input(), 'rU') as input_file: # Python 2 with open(raw_input(), 'rU') as input_file: 

This prompts the user for text input and returns it as a string. In your case, this will prompt for a file path to be input.

If you add an argument to this function, it prints something without a newline before input is requested, for example:

input("File: ") 

Here's an example program which uses the input function:

answer = input() print("Your answer was: " + answer) 

When run:

foo Your answer was: foo 
Sign up to request clarification or add additional context in comments.

2 Comments

Might also want to add a prompt for the input and raw_input functions
@sshashank124 Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.