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

Creating a file within Python 2 script to write to , using argv

我想使用 argv 通过命令行创建一个文件(示例 >>> python thisscript.py nonexistent.txt )然后从我的代码中写入它。我使用了 open(nonexistent, '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 语句,您应该 read up about it。使用所谓的上下文管理器打开和关闭文件是一种更安全的方法。