如果文件不存在,如何创建,如果存在则不截断 - Python27

时间:2016-11-16 14:39:27

标签: python python-2.7 file io

我有这段代码

 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),但它没有任何影响,它不会寻找文件的开头。

4 个答案:

答案 0 :(得分:1)

我们假设您有一个内容为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

而且,正如您所怀疑的那样,您将无法在0模式下寻求a+。您可能会看到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

答案 1 :(得分:0)

您可以检查文件是否存在,然后进行相应的分支,如下所示:

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

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

希望这有帮助!

答案 2 :(得分:0)

使用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 :(得分:0)

您可以使用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()