【问题标题】:open() in Python does not create a file if it doesn't exist如果文件不存在,Python 中的 open() 不会创建文件
【发布时间】:2011-02-27 08:58:17
【问题描述】:

如果文件存在,则以读/写方式打开文件的最佳方法是什么,或者如果不存在,则创建它并以读/写方式打开它?根据我的阅读,file = open('myfile.dat', 'rw') 应该这样做,对吧?

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

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

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

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

【问题讨论】:

  • 正如 S.Mark 提到的,这应该“正常工作”。封闭目录是否可写?
  • muksie 在下面的回答有效(并且 baloo 也是如此),但为了完整起见,封闭的目录可由用户和组写入,而不是其他(我在 linux 系统上...所以权限 775换句话说),确切的错误是 IOError: no such file or directory。谢谢你们的帮助。
  • 确保file 的所有前导文件夹都存在。

标签: python linux file-io file-permissions


【解决方案1】:

您应该将openw+ 模式一起使用:

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

【讨论】:

  • w 截断现有文件。文档:模式'r+''w+''a+' 打开文件进行更新(注意'w+' 会截断文件)。
  • 这成功了。谢谢。我现在因为不阅读规范而觉得自己像个白痴。我不认为'rw'在那里甚至是可以接受的。我一定是在想别的东西。
  • 请注意,如果文件不存在,a+ 会创建一个文件,并且至关重要的是,它会一直查找该文件。因此,如果您在以这种方式打开后立即阅读,您将一无所获。你需要先回到起点:f.seek(0)
  • 这不是解决方案。 问题是目录。要么脚本缺乏在该目录中创建文件的权限,要么该目录根本不存在。 open('myfile.dat', 'w') 就足够了。
【解决方案2】:

以下方法的优点是文件在块的末尾正确关闭,即使在途中引发了异常。它相当于try-finally,但要短得多。

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

a+ 打开一个文件以进行追加和读取。文件指针是 如果文件存在,则在文件末尾。该文件在 附加模式。如果文件不存在,则创建一个新文件 读写。 -Python file modes

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” - 请参阅堆栈溢出问题 Python file modes detail

【讨论】:

  • 我尝试使用 open(filename, 'a+') as myfile: 并得到 IOError: [Errno 2] No such file or directory: - 为什么它不创建文件?
  • @Loretta 你检查过filename的值吗?
  • 是的,我做到了。它是一个 unicode 字符串。我还尝试使用 open('{}.txt'.format(filename), 'a+') as myfile:
  • 我没有使用路径。我尝试了 open('test.txt', 'a+') 它在 os.stat(myfile).st_size == 0 的行中出现以下异常 'TypeError: coercing to Unicode: need string or buffer, file found':
  • 您需要正确定义编码才能使其正常工作。 stackoverflow.com/q/728891/3701431
【解决方案3】:

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

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

【讨论】:

  • 在打开文件之前测试它是不好的,因为它可能导致竞争条件(文件在打开之前被删除)。竞争条件有时可用于利用系统中的漏洞。 “a+”模式是打开文件的最佳方式:它创建一个新文件,并附加到现有文件。不要忘记将其包装在 try/except 中。
  • 计算模式写入或追加没有兴趣。如果文件不存在,则追加模式创建它。
【解决方案4】:
'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
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 版]

【讨论】:

    【解决方案5】:

    把“rw”改成“w+”

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

    【讨论】:

      【解决方案6】:
      >>> import os
      >>> if os.path.exists("myfile.dat"):
      ...     f = file("myfile.dat", "r+")
      ... else:
      ...     f = file("myfile.dat", "w")
      

      r+ 表示读/写

      【讨论】:

      【解决方案7】:

      从 python 3.4 开始,您应该使用 pathlib 来“触摸”文件。
      这是一个比此线程中建议的解决方案更优雅的解决方案。

      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)
      

      【讨论】:

      • touch 在使用时会更新上次修改时间。
      • @DavidParks 好点,刚刚测试过,在 ext4 文件系统和 python3.7.2 上确实如此。我不认为这是预期或期望的行为,也许这是 python 的错误?
      • 在 linux 的命令行中使用 touch 时也是如此,所以我认为这是预期的行为。
      【解决方案8】:

      我的回答:

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

      【讨论】:

        【解决方案9】:

        用途:

        import os
        
        f_loc = r"C:\Users\Russell\Desktop\myfile.dat"
        
        # Create the file if it does not exist
        if not os.path.exists(f_loc):
            open(f_loc, 'w').close()
        
        # Open the file for appending and reading
        with open(f_loc, 'a+') as f:
            #Do stuff
        

        注意:打开文件后必须关闭文件,with 上下文管理器是让 Python 为您处理这一切的好方法。

        【讨论】:

          【解决方案10】:

          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

          【讨论】:

            【解决方案11】:

            你想对文件做什么?只写还是读写?

            'w''a' 将允许写入并在文件不存在时创建文件。

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

            【讨论】:

            • 在打开之前测试是否存在可能会引入竞争条件。在这种情况下可能没什么大不了的,但要记住一些事情。
            • "如果您需要从文件中读取,文件必须在您打开之前存在。"谢谢你拯救了我的理智。
            【解决方案12】:

            我认为是r+,而不是rw。我只是一个初学者,这就是我在文档中看到的内容。

            【讨论】:

              【解决方案13】:

              对于 Python 3+,我会这样做:

              import os
              
              os.makedirs('path/to/the/directory', exist_ok=True)
              
              with open('path/to/the/directory/filename', 'w') as f:
                  f.write(...)
              

              所以,问题是with open 在目标目录存在之前无法创建文件。我们需要创建它,然后w 模式在这种情况下就足够了。

              【讨论】:

              • 小心这个!如果文件存在,它将截断内容。
              • 嗨@NONONONONO,是的,w 模式就是这样做的。如果要保留现有内容,可以使用a追加模式。参考open() doc
              【解决方案14】:

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

              【讨论】:

                【解决方案15】:

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

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

                【讨论】:

                  【解决方案16】:

                  所以您想将数据写入文件,但前提是文件不存在?

                  这个问题很容易通过使用鲜为人知的 x 模式来 open() 而不是通常的 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'
                    >>>
                  

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

                  【讨论】:

                    【解决方案17】:
                    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)
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2012-05-10
                      • 1970-01-01
                      • 1970-01-01
                      • 2021-12-26
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2016-02-08
                      相关资源
                      最近更新 更多