[英]Creating a file within Python 2 script to write to , using argv
我想使用argv通過命令行(例如>>> python thisscript.py nonexistent.txt)創建文件,然后從我的代碼中寫入文件。 我已經使用過open(unexistent,'w')。write()命令,但似乎只能打開並寫入已經存在的文件。 我想念什么嗎?
這是我的代碼。 只要我要寫入的文件已經存在,它就可以工作
from sys import argv
script, letter_file = argv
string_let='abcdefghijklmnopqrstuvwxyz'
list_of_letters = list(string_let)
f = open(letter_file)
wf = open(letter_file, 'w')
def write_func():
for j in range(26):
for i in list_of_letters:
wf.write(i)
write_func()
wf.close()
raw_input('Press <ENTER> to read contents of %r' % letter_file)
output = f.read()
print output
但是當文件不存在時,這就是我在終端中返回給我的內容
[admin@horriblehost-mydomain ~]$ python alphabetloop.py nonexistent.txt
Traceback (most recent call last):
File "alphabetloop.py", line 14, in <module>
f = open(letter_file)
IOError: [Errno 2] No such file or directory: 'nonexistent.txt'
[admin@horriblehost-mydomain ~]$
open(filename, 'w')
不僅適用於現有文件。 如果文件不存在,它將創建它:
$ ls mynewfile.txt
ls: mynewfile.txt: No such file or directory
$ python
>>> with open("mynewfile.txt", "w") as f:
... f.write("Foo Bar!")
...
>>> exit()
$ cat mynewfile.txt
Foo Bar!
請注意, 'w'
將始終清除文件的現有內容。 如果要追加到現有文件的末尾,或者要創建不存在的文件,請使用'a'
(即open("mynewfile.txt", "a")
)
這可以通過以下方式完成:
import sys
if len(sys.argv)<3:
print "usage: makefile <filename> <content>"
else:
open(sys.argv[1],'w').write(sys.argv[2])
演示:
paul@home:~/SO/py1$ python makefile.py ./testfile feefiefoefum
paul@home:~/SO/py1$ ls
makefile.py makefile.py~ testfile
paul@home:~/SO/py1$ cat testfile
feefiefoefum
注意:在sys.argv
,元素[0]
是腳本的名稱,后續元素包含用戶輸入
如果使用“ w”標志打開文件,則將覆蓋文件的內容。 如果文件不存在,它將為您創建文件。
如果您要添加到文件中,則應使用“ a”標志打開它。
這是一個例子:
with open("existing.txt", "w") as f:
f.write("foo") # overwrites anything inside the file
existing.txt
現在包含“ foo”
with open("existing.txt", "a") as f:
f.write("bar") # appends 'bar' to 'foo'
existing.txt
現在包含“ foobar”
另外,如果您不熟悉我在上面使用的with
語句,則應該閱讀有關它的內容 。 這是使用上下文管理器打開和關閉文件的更安全的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.