1

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:
P.J.
  • 217
  • 2
  • 4
  • 13

1 Answers1

4

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
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78