代码之家  ›  专栏  ›  技术社区  ›  Sinux1

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

  •  0
  • Sinux1  · 技术社区  · 10 年前

    我想使用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 回复  |  直到 10 年前
        1
  •  1
  •   Jake Griffin    10 年前

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

        2
  •  1
  •   Paul    10 年前

    这可以通过以下方式实现:

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

        3
  •  1
  •   Hosack    10 年前

    如果打开带有“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'
    

    现有.txt 现在包含“foobar”

    此外,如果您不熟悉 with 我上面使用的语句,您应该 read up about it 。使用所谓的上下文管理器打开和关闭文件是一种更安全的方法。

    推荐文章