2016-11-16 16 views
-1

私はこのコード- 私が欲しいPython27

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)を持っていました、それは影響を与えない、それはファイルの開始を求めることはありません。

+0

@StamKaly、どこで取得できましたか? –

+0

@AhsanulHaque彼は彼のコメントを削除しましたhaha – Umair

答えて

0

あなたは、ファイルが存在するかどうかを確認した後、そのように応じて分岐することができます。

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

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

・ホープ、このことができますが!

+0

他に方法はありませんか?私は多分ファイルモードを悪用しているかもしれませんが、私はおそらく私がファイルモードを悪用していることを意味します。 – Umair

+2

OPは彼がファイルモードで問題を解決できるかどうかを尋ねるので、答えに何もありません。 –

+0

マルチプロセッシングまたはマルチスレッドの状況では、競合状態が発生します。 – RemcoGerlich

0

使用os.path.isfile():ファイルの物乞いへの書き込みについてあなたの2番目の質問については

import os 

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

、その後、a+を使用しないでください。 See here for how to prepend to a file。あなただけ行う、ファイルの先頭から書き込みをする必要がある場合は

first line 
second line 
third line 

:あなたがコンテンツを持つファイル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) 
1

私はここで関連ビットを投稿します
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にアクセスすることはできません。

はい、あなたはこの構成ではJSONをダンプし、まだインデントすることができます:あなたはhere

編集から詳細が表示される場合があります。デモ:

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 
+0

ファイル内の最終出力は何ですか? – Umair

+0

ファイルに書き込むために 'json.dump(_tempDict、fp = f、indent = 2、ensure_ascii = False)'を使っていました.. note 'ident'フラグ... anserを使って識別できるものがあります – Umair

+0

@Umair 、更新された答えを参照してください。 –

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() 
関連する問題