2017-10-11 40 views
0

我在書中的練習15一章中學習python。 由於本書建議在bash上運行命令「python ex15.py ex15_sample.txt」,我只是遵循這個命令。在執行此程序之前,我是否必須創建另一個文本文件?

from sys import argv 

script, filename = argv 

txt = open(filename) 

print "Here's your file %r:" % filename 
print txt.read() 

print "Type the filename again:" 
file_again = raw_input("> ") 

txt_again = open(file_again) 

print txt_again.read() 

但是,在bash上出現這樣的錯誤。

Traceback (most recent call last): 
    File "ex15.py", line 5, in <module> 
    txt = open(filename) 
IOError: [Errno 21] Is a directory: 'ex15_sample.txt' 

我用「的mkdir ex15_sample.txt」,甚至試圖以文字文本文件在同一目錄,但錯誤還是出現了一個文件。

+2

如果你在bash上使用'touch' - >'touch ex15_sample.txt'。 'mkdir'創建一個空目錄。 –

+1

FWIW,SO Python聊天室常客[不建議LPTHW](http://sopython.com/wiki/LPTHW_Complaints)。如果它在爲你工作,那太好了,但請注意,這本書有幾個問題。另外請注意,Python 2將在2020年達到其生命終結,所以您應該學習Python 3,除非您需要Python 2來處理遺留代碼。 –

回答

1

上殼,你會首先看到的運行man mkdir是這樣的:

NAME 
    mkdir -- make directories 

,顧名思義,mkdir用於創建目錄。在這種情況下,會創建一個名爲ex15_sample.txt的空目錄,因此open會引發您看到的錯誤。

如果你想創建一個文件,使用touch

touch ex15_sample.txt 

touch更新文件的mtime如果它存在,或創建文件,如果它不。

或者,使用cat>

cat > ex15_sample.txt 

運行的第一個命令後,打Ctrl+C,創建一個空文件。

0

您正在使用mkdir創建一個目錄。

要在終端的文本文件類型,在同一目錄下你的Python文件:

nano ex15_sample.txt 

這將讓你到一個文本編輯器,只需鍵入您的文本,並保存按crtl+x並確認按yenter

現在您可以打開文件。

相關問題