user2877540
user2877540

Reputation: 35

How to print quotes around a variable user inputted. Python

info = []
file = input("Enter a file ")

try:
    infile = open(file, 'r')

except IOError:
    print("Error: file" ,file, "could not be opened.")

if user enters file as filetest.txt,
This is my code.. I would like it to print Error: file "filetest.txt" could not be opened. Thanks for the help.

Upvotes: 0

Views: 110

Answers (3)

user2555451
user2555451

Reputation:

This works:

print('Error: file "{}" could not be opened.'.format(file))

See a demonstration below:

>>> file = "filetest.txt"
>>> print('Error: file "{}" could not be opened.'.format(file))
Error: file "filetest.txt" could not be opened.
>>>

In Python, single quotes can enclose double quotes and vice-versa. Also, here is a reference on str.format.


Lastly, I wanted to add that open defaults to read mode. So, you can actually just do this:

infile = open(file)

However, some people like to explicitly put the 'r', so that choice is up to you.

Upvotes: 6

mbdavis
mbdavis

Reputation: 4010

Escape the quotes with a backslash

myFile = "myfile.txt"
print("Error: file \"" + myFile + "\" could not be opened.")

Prints:

Error: file "myfile.txt" could not be opened.

Upvotes: 1

John Spong
John Spong

Reputation: 1381

print("Error: file \"{}\" could not be opened.".format(file))

Be careful, however, that file is a built-in type in python. Per convention, your variable should be named file_

Upvotes: 2

Related Questions