使用argv在Python 2脚本中创建要写入的文件

时间:2015-08-04 23:12:25

标签: python argv sys

我想使用argv使用命令行创建文件(例如>>> python thisscript.py nonexistent.txt)然后从我的代码中写入它。我使用了open(不存在,'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 ~]$ 

3 个答案:

答案 0 :(得分:1)

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")

答案 1 :(得分:1)

这可以通过以下方式完成:

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]是脚本的名称,后续元素包含用户输入

答案 2 :(得分:1)

如果使用“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声明,您应该read up about it。使用所谓的Context Manager打开和关闭文件是一种更安全的方法。