【问题标题】:How to create file if it does not exists, if exists then don't truncate - Python27如果文件不存在如何创建文件,如果存在则不要截断 - Python27
【发布时间】:2017-03-30 19:33:13
【问题描述】:

我有这个代码

 with codecs.open("file.json", mode='a+', encoding='utf-8') as f:

我想要:

1) 如果文件不存在,则创建文件,并从文件开头开始写入。

2) 如果存在,先读取它并截断它,然后再写一些东西。

我在某个地方找到了这个

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

a+ 模式最适合我,但它只能让我写在文件末尾,

a+模式下,我打开文件后立即有这个f.seek(0),但它没有影响,它不会寻找文件的开头。

【问题讨论】:

  • @StamKaly,你从哪里得到的?
  • @AhsanulHaque 他删除了他的评论哈哈

标签: python python-2.7 file io


【解决方案1】:

您可以检查文件是否存在,然后像这样进行相应的分支:

import os.path
file_exists = os.path.isfile(filename) 

if file_exists:
    # do something
else:
    # do something else

希望这会有所帮助!

【讨论】:

  • 没有别的办法了吗?我的意思是我可能会滥用文件模式
  • 投反对票,因为 OP 询问他是否可以解决文件模式的问题,而答案中没有任何内容。
  • 在多处理或多线程情况下,存在竞争条件。
  • 原始问题并没有具体询问是否可以通过文件模式解决问题。他提到它“最适合他”,我只是提供了一个替代解决方案。不过,在比赛条件方面还算公平。
【解决方案2】:

使用os.path.isfile():

import os

if os.path.isfile(filename):
    # do stuff
else:
    # do other stuff

关于第二个关于写入请求文件的问题,请不要使用a+See here for how to prepend to a file。我将在此处发布相关位:

# credit goes to @eyquem. Not my code

def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

【讨论】:

    【解决方案3】:

    假设你有一个文件a,内容如下:

    first line
    second line
    third line 
    

    如果你需要从文件的开头写,只需:

    with open('a','r+') as f:
        f.write("forth line")
    

    输出:

    forth line
    second line
    third line
    

    如果您需要删除当前内容并从头开始编写,请执行以下操作:

    with open('a','r+') as f:
        f.write("forth line")
        f.truncate()
    

    输出:

    forth line
    

    如果您需要在现有文件之后追加,请执行以下操作:

    with open('a','a') as f:
        f.write("forth line")
    

    输出:

    first line
    second line
    third line
    forth line
    

    而且,正如您所怀疑的,您将无法在a+ 模式下搜索0。您可能会看到来自here的详细信息

    编辑:

    是的,您可以使用此配置转储 json 并且仍然缩进。演示:

    dic = {'a':1,"b":2}
    
    import json
    with open('a','r+') as f:
        json.dump(dic,f, indent=2)
    

    输出:

    {
      "a": 1, 
      "b": 2
    }third line
    

    【讨论】:

    • 文件中的最终输出是什么?
    • 我使用json.dump(_tempDict, fp=f, indent=2, ensure_ascii=False) 写入文件.. 注意ident 标志... 有什么我可以用你的分析器识别的吗
    【解决方案4】:

    您可以使用os.open 打开文件,以便能够搜索并拥有更多控制权,但您将无法使用codecs.open 或上下文管理器,因此需要更多的体力劳动:

    import os
    f = os.fdopen(os.open(filename, os.O_RDWR | os.O_CREAT), 'r+')
    try:
        content = f.read()
        f.seek(0)
        f.truncate()
        f.write("Your new data")
    finally:
        f.close()
    

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 2012-05-10
      • 2020-08-18
      • 2010-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2014-07-20
      • 2016-06-26
      相关资源
      最近更新 更多