首页 文章

如果文件不存在,Python中的open()不会创建文件

提问于
浏览
514

打开文件作为读/写(如果存在)或不存在的最佳方法是什么,然后创建它并将其作为读/写打开?从我读到的, file = open('myfile.dat', 'rw') 应该这样做,对吧?

它对我不起作用(Python 2.6.2),我想知道它是否是版本问题,或者不应该像那样或者什么工作 .

最重要的是,我只需要解决问题的方法 . 我很好奇其他的东西,但我需要的是一个很好的方式来做开场部分 .

更新:封闭目录可由用户和组写入,而不是其他(我在Linux系统上...所以权限775换句话说),确切的错误是:

IOError:没有这样的文件或目录 .

16 回答

  • 104

    好的做法是使用以下内容:

    import os
    
    writepath = 'some/path/to/file.txt'
    
    mode = 'a' if os.path.exists(writepath) else 'w'
    with open(writepath, mode) as f:
        f.write('Hello, world!\n')
    
  • 1

    所以你想把数据写入文件,但只有它还不存在?

    通过使用鲜为人知的x模式来打开()而不是通常的w模式,可以很容易地解决这个问题 . 例如:

    >>> with open('somefile', 'wt') as f:
     ...     f.write('Hello\n')
    ...
    >>> with open('somefile', 'xt') as f:
    ...     f.write('Hello\n')
    ...
     Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
    FileExistsError: [Errno 17] File exists: 'somefile'
      >>>
    

    如果文件是二进制模式,请使用mode xb而不是xt .

  • 7

    我认为这是r,而不是rw . 我'm just a starter, and that'是我在文档中看到的 .

  • 667
    >>> import os
    >>> if os.path.exists("myfile.dat"):
    ...     f = file("myfile.dat", "r+")
    ... else:
    ...     f = file("myfile.dat", "w")
    

    r表示读/写

  • 6
    '''
    w  write mode
    r  read mode
    a  append mode
    
    w+  create file if it doesn't exist and open it in write mode
    r+  create file if it doesn't exist and open it in read mode
    a+  create file if it doesn't exist and open it in append mode
    '''
    

    例:

    file_name = 'my_file.txt'
    f = open(file_name, 'w+')  # open file in write mode
    f.write('python rules')
    f.close()
    

    我希望这有帮助 . [仅供参考使用python版本3.6.2

  • 0
    import os, platform
    os.chdir('c:\\Users\\MS\\Desktop')
    
    try :
        file = open("Learn Python.txt","a")
        print('this file is exist')
    except:
        print('this file is not exist')
    file.write('\n''Hello Ashok')
    
    fhead = open('Learn Python.txt')
    
    for line in fhead:
    
        words = line.split()
    print(words)
    
  • 25

    open('myfile.dat', 'a') 适合我,很好 .

    在py3k你的代码引发 ValueError

    >>> open('myfile.dat', 'rw')
    Traceback (most recent call last):
      File "<pyshell#34>", line 1, in <module>
        open('myfile.dat', 'rw')
    ValueError: must have exactly one of read/write/append mode
    

    在python-2.6中它引发了 IOError .

  • 32

    使用:

    import os
    
    f_loc = r"C:\Users\Russell\Desktop\ip_addr.txt"
    
    if not os.path.exists(f_loc):
        open(f_loc, 'w').close()
    
    with open(f_loc) as f:
        #Do stuff
    

    确保在打开文件后关闭它们 . with 上下文管理器将为您执行此操作 .

  • 5

    从python 3.4开始,你应该使用 pathlib 到"touch"文件 .
    它比这个帖子中提出的解决方案更优雅 .

    from pathlib import Path
    
    filename = Path('myfile.txt')
    filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
    file = open(filename)
    

    目录也一样:

    filename.mkdir(parents=True, exist_ok=True)
    
  • 4

    将W写入文件,截断(如果存在),r读取文件,创建一个(如果不存在但不写入(并返回null))或创建新文件或附加到现有文件 .

  • 5

    以下方法的优点是文件 properly closed 在块's end, even if an exception is raised on the way. It' s相当于 try-finally ,但更短 .

    with open("file.dat","a+") as f:
        f.write(...)
        ...
    

    a打开文件以进行追加和读取 . 如果文件存在,则文件指针位于文件的末尾 . 该文件以追加模式打开 . 如果该文件不存在,则会创建一个用于读写的新文件 . -Python文件模式

    seek() method设置文件的当前位置 .

    f.seek(pos [, (0|1|2)])
    pos .. position of the r/w pointer
    [] .. optionally
    () .. one of ->
      0 .. absolute position
      1 .. relative position to current
      2 .. relative position from end
    

    只允许“rwab”字符;必须有一个“rwa” - 请参阅Stack Overflow问题Python文件模式的详细信息 .

  • 4

    我的答案:

    file_path = 'myfile.dat'
    try:
        fp = open(file_path)
    except IOError:
        # If not exists, create the file
        fp = open(file_path, 'w+')
    
  • 6

    你想用文件做什么?只写入它或同时读写?

    'w','a'将允许写入,如果文件不存在,将创建该文件 .

    如果需要从文件中读取,则必须在打开文件之前存在该文件 . 您可以在打开它之前测试它的存在或使用try / except .

  • 4

    将“rw”改为“w”

    或使用'a'进行追加(不删除现有内容)

  • 14

    你应该使用 openw+ 模式:

    file = open('myfile.dat', 'w+')
    
  • 29

    如果你想打开它来读写,我假设你不想在打开它时截断它,你希望能够在打开文件后立即读取它 . 所以这是我正在使用的解决方案:

    file = open('myfile.dat', 'a+')
    file.seek(0, 0)
    

相关问题