簡體   English   中英

在執行該程序之前,我是否需要制作另一個文本文件?

[英]Do I have to make another text file before executing this program?

我在這本書的練習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”制作了一個文件,甚至嘗試將文本文件放在同一目錄下,但錯誤仍然出現。

在shell上運行man mkdir ,您會看到的第一件事是:

NAME
     mkdir -- make directories

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

如果要創建文件,請使用touch

touch ex15_sample.txt

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

或者,將cat>使用:

cat > ex15_sample.txt

運行第一個命令后, Ctrl+C來創建一個空文件。

您正在使用mkdir創建目錄。

要在終端中創建文本文件,請在與您的python文件相同的目錄中輸入:

nano ex15_sample.txt

這將使您進入文本編輯器,只需鍵入文本並保存按crtl+x並確認按yenter

現在,您可以打開文件了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM