Python 如果文件不存在,如何创建该文件,如果存在,则不';t截形蟒蛇27

Python 如果文件不存在,如何创建该文件,如果存在,则不';t截形蟒蛇27,python,python-2.7,file,io,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

我有这个密码

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

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

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

if file_exists:
    # do something
else:
    # do something else
希望这有帮助

使用
os.path.isfile()

至于你的第二个问题,关于写一个文件,那么不要使用
a+
。我将在这里发布相关信息:

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

假设您有一个包含以下内容的文件
a

first line
second line
third line 
如果需要从文件开始写入,只需执行以下操作:

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

forth line
second line
third line
forth line
first line
second line
third line
forth line
{
  "a": 1, 
  "b": 2
}third line
如果需要删除当前内容并从头开始写入,请执行以下操作:

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

forth line
second line
third line
forth line
first line
second line
third line
forth line
{
  "a": 1, 
  "b": 2
}third line
如果需要在现有文件后追加,请执行以下操作:

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

forth line
second line
third line
forth line
first line
second line
third line
forth line
{
  "a": 1, 
  "b": 2
}third line
而且,正如您所怀疑的,您将无法在
a+
模式下搜索
0
。您可能会从中看到详细信息

编辑:

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

dic = {'a':1,"b":2}

import json
with open('a','r+') as f:
    json.dump(dic,f, indent=2)
输出:

forth line
second line
third line
forth line
first line
second line
third line
forth line
{
  "a": 1, 
  "b": 2
}third line

您可以使用操作系统打开文件。打开可以搜索并获得更多控制,但您将无法使用编解码器。打开或上下文管理器,因此需要更多的手动劳动:

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

没有别的办法了?我的意思是,我想我可能误用了文件模式,因为OP问他是否可以用文件模式解决这个问题,答案中没有任何内容。在多处理或多线程的情况下,有一个竞争条件。最初的问题并没有特别问这个问题是否可以用文件模式解决。他提到“最适合他”,我只是提供了一个替代方案。不过,关于比赛条件,这很公平。@StamKaly,你从哪里得到的?@AhsanulHaque他删除了他的评论HahawWhat将是文件中的最终输出?我使用的是
json.dump(\u tempDict,fp=f,indent=2,确保\u ascii=False)
来写入文件。。注意
ident
标志。。。有什么我可以用你的答案识别的吗