hcd
hcd

Reputation: 1

Asking for input in python, allow direct entry or a text file

Is it possible to use a typical x=input('') where someone could either do a direct entry, or they can say read from a file? Example:

x=input("")
for line in x:
    print('Hi %s'%line)

The person can then either type their name, or put a text file to read from? If so, how?

Upvotes: 0

Views: 52

Answers (1)

Malik Brahimi
Malik Brahimi

Reputation: 16711

Use a try and except to see if the passed string is a valid path:

x = input()

try:
    with open(x) as data:
        for name_line in data:
            print('Hi ' + name_line)

except:
    print('Hi ' + x)

Upvotes: 1

Related Questions