【问题标题】:Create a file if it doesn't exist如果文件不存在,则创建一个文件
【发布时间】:2016-06-18 20:53:13
【问题描述】:

我正在尝试打开一个文件,如果该文件不存在,我需要创建它并打开它进行写入。到目前为止我有这个:

#open file for reading
fn = input("Enter file to open: ")
fh = open(fn,'r')
# if file does not exist, create it
if (!fh) 
fh = open ( fh, "w")

错误消息显示if(!fh) 行存在问题。我可以像在 Perl 中一样使用exist 吗?

【问题讨论】:

标签: python createfile


【解决方案1】:

如果你不需要原子性,你可以使用 os 模块:

import os

if not os.path.exists('/tmp/test'):
    os.mknod('/tmp/test')

更新

正如 Cory Klein 提到的,在 Mac OS 上使用 os.mknod() 你需要 root 权限,所以如果你是 Mac OS 用户,你可以使用 open() 而不是 os.mknod()

import os

if not os.path.exists('/tmp/test'):
    with open('/tmp/test', 'w'): pass

【讨论】:

  • macOS requires sudo privileges to run mknod 所以这不太可能移植到 Mac,除非您使用 sudo 运行 python 脚本。
  • 这会在exists()open() 之间创建一个竞争条件。
  • 它是如何产生竞争条件的? exists() 在 open() 执行之前被测试。
  • 因为exists()open() 是两个独立的调用,所以这个解决方案不是原子的。理论上,在这两个函数调用之间有一段时间,另一个程序也可能会检查文件的存在并在没有找到文件的情况下创建它。
  • 在windows上不行,os没有属性mknod。
【解决方案2】:
'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in (over)write mode
    [it overwrites the file if it already exists]
r+  open an existing file in read+write mode
a+  create file if it doesn't exist and open it in append mode
'''

示例:

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

我希望这会有所帮助。 [仅供参考,我使用的是 python 3.6.2 版]

【讨论】:

  • r+ 不创建任何文件。还提到herehere(in the description) r+ 用于以读写模式打开文件。纠正它,因为它可能会混淆人们:)
  • w+ 也会清除文件的内容。 Here 是对每种模式的完整(较长)描述。
  • 它在 Windows 上不起作用:发生异常:FileNotFoundError
【解决方案3】:

首先,在 Python 中没有 ! 运算符,那就是 not。但是open 也不会静默失败——它会抛出异常。并且块需要正确缩进 - Python 使用空格来指示块包含。

因此我们得到:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except IOError:
    file = open(fn, 'w')

【讨论】:

  • 我一直在试图弄清楚为什么这比open(fn, 'a').close() 更可取。是不是因为隐含的seek 可能太贵了?
【解决方案4】:

这是一个快速的两行代码,如果文件不存在,我可以使用它快速创建它。

if not os.path.exists(filename):
    open(filename, 'w').close()

【讨论】:

  • 简洁明了。请删除“文件名”周围的双引号。
  • 似乎如果文件路径不存在,您也可以在“x”模式下打开它,因为您已经确定该文件不存在。
  • 不用说import os必须在使用这两条线之前声明。
【解决方案5】:

使用 input() 意味着 Python 3,最近的 Python 3 版本已弃用 IOError 异常(它现在是 OSError 的别名)。因此,假设您使用的是 Python 3.3 或更高版本:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except FileNotFoundError:
    file = open(fn, 'w')

【讨论】:

    【解决方案6】:

    我认为这应该可行:

    #open file for reading
    fn = input("Enter file to open: ")
    try:
        fh = open(fn,'r')
    except:
    # if file does not exist, create it
        fh = open(fn,'w')
    

    另外,当你想打开的文件是fn时,你写错了fh = open ( fh, "w")

    【讨论】:

    • 您假设该文件无法打开,因为它不存在。可能是您没有读取权限,或者文件名在某些方面无效。光秃秃的except 不是个好主意。
    • 我明白,(现在)但这对于他的编程水平来说已经足够有效了,虽然我们不是在教他编程的礼仪或为class 做准备。
    • 好吧,这个可怜的家伙来自 Perl,所以他需要他能得到的所有帮助。
    • 这让我很开心。我们可以解释其中的复杂性,但是,我想睡觉,也许我会在早上向他解释路径,还是你想要?
    • 你不需要写一篇关于有效异常处理的论文,给他很好的例子就行了。还有其他答案可以做到这一点。
    【解决方案7】:

    请注意,每次使用此方法打开文件时,文件中的旧数据都会被破坏,无论是“w+”还是“w”。

    import os
    
    with open("file.txt", 'w+') as f:
        f.write("file is opened for business")
    

    【讨论】:

    • 代码中有错字。应该是with open('file.txt', 'w+') as f:
    • @Flux 修正错字
    • with 写入新文件的答案应该放在最上面。我会使用a+ 附加到文件以避免覆盖。
    【解决方案8】:

    如果您知道文件夹位置并且文件名是唯一未知的,

    open(f"{path_to_the_file}/{file_name}", "w+")
    

    如果文件夹位置也未知

    尝试使用

    pathlib.Path.mkdir
    

    【讨论】:

      【解决方案9】:

      首先让我提一下,您可能不想创建最终可以打开以进行读取或写入的文件对象,具体取决于不可重现的条件。您需要知道可以使用哪些方法,读取或写入,这取决于您要对文件对象做什么。

      也就是说,您可以按照 That One Random Scrub 建议的方式进行操作,使用 try: ... except:。实际上这是建议的方式,根据蟒蛇的座右铭“请求宽恕比请求许可更容易”。

      但您也可以轻松测试是否存在:

      import os
      # open file for reading
      fn = raw_input("Enter file to open: ")
      if os.path.exists(fn):
          fh = open(fn, "r")
      else:
          fh = open(fn, "w")
      

      注意:使用 raw_input() 而不是 input(),因为 input() 会尝试执行输入的文本。如果您不小心想测试文件“导入”,您会收到 SyntaxError。

      【讨论】:

      • 有关input()raw_input() 的cmets 仅适用于Python 2。Python 3 已将raw_input() 替换为input(),并且input() 的“旧”用法已不复存在。跨度>
      • 这是可能的,并且将是/是一个很好的改进,使其更直观。
      猜你喜欢
      • 2012-04-08
      • 2011-01-19
      • 2014-01-02
      • 2012-05-10
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多