2016-11-16 1 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+ 모드가 나를 가장 잘 맞는 있지만 발견 그것은 단지 제가 파일을 연 후 즉시 f.seek(0)a+ 모드로

, 파일의 마지막에 기입 할 것을 무엇 ,하지만 영향을 미치지 않습니다, 그것은 파일의 시작을 추구하지 않습니다.

+0

@StamKaly, 어디서 얻었습니까? –

+0

@AssanulHaque 그는 그의 코멘트를 삭제했다 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()는 :

파일의 구걸에 작성하는 방법에 대한 두 번째 질문에 관해서는
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) 
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을 찾을 수 없습니다.당신은 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 
+0

파일의 최종 출력 내용은 무엇입니까? – Umair

+0

파일에 쓰려면'json.dump (_tempDict, fp = f, indent = 2, ensure_ascii = False)'를 사용하고 있었다 .. note'ident' 플래그 ... anser를 사용하여 식별 할 수있는 뭔가가있다. – Umair

+0

@Umair , 업데이트 된 답변을 참조하십시오. –

0

당신이 추구하고보다 효율적으로 제어 할 수 있도록 os.open을 사용하여 파일을 열 수 있습니다,하지만 당신은 다음 codecs.open 또는 컨텍스트 관리자를 사용할 수 없습니다 , 좀 더 수작업으로 처리됩니다.

관련 문제