info = []
file = input("Enter a file ")
try:
infile = open(file, 'r')
except IOError:
print("Error: file" ,file, "could not be opened.")
,
這是我的代碼..我想它打印錯誤:文件「filetest.txt」無法打開。 感謝您的幫助。如何打印輸入變量用戶的引號。 Python的
info = []
file = input("Enter a file ")
try:
infile = open(file, 'r')
except IOError:
print("Error: file" ,file, "could not be opened.")
,
這是我的代碼..我想它打印錯誤:文件「filetest.txt」無法打開。 感謝您的幫助。如何打印輸入變量用戶的引號。 Python的
print("Error: file \"{}\" could not be opened.".format(file))
但要小心,file
是python中的內置類型。按照慣例,您的變量應該命名爲file_
這工作:
print('Error: file "{}" could not be opened.'.format(file))
請參見下面的演示:
>>> file = "filetest.txt"
>>> print('Error: file "{}" could not be opened.'.format(file))
Error: file "filetest.txt" could not be opened.
>>>
在Python中,單引號可以包圍雙引號,反之亦然。另外,這裏是str.format
的參考。
最後,我想補充一點,open
默認爲讀取模式。所以,實際上你可以只是這樣做:
infile = open(file)
然而,有些人喜歡明確提出了'r'
,這樣的選擇是由你。
用反斜槓逃逸引號
myFile = "myfile.txt"
print("Error: file \"" + myFile + "\" could not be opened.")
打印:
Error: file "myfile.txt" could not be opened.
請不要使用'file'作爲變量名(這同樣適用於'list','dict'漂亮很多所有類型) – inspectorG4dget
@ user2877540接受一個答案 – mbdavis