2013-12-15 7 views
1

파일 끝 부분에 문자열을 추가하려했지만 작동하지 않습니다. 이 오류를 얻을 :파이썬에서 파일 끝에 뭔가 추가 하시겠습니까?

IOError: (9, 'Bad file descriptor') 

나는 #hashcomment에 부합 그것은 아래의 코드에서의 123에 그것을 얻을하지만 표시 :

pluginlokacija2 = os.path.realpath("%s/plugins"%os.getcwd()) 
fo = open("%s/TwistedJobs/config.yml"%pluginlokacija2, "wb") 
old = fo.read() #this is line no. 123 
fo.seek(0) 
fo.write("%s\n- %s\n " % (old, event.getPlayer().getName())) 
fo.close 

사전에 감사, 아마르을!

P. 더 자세한 정보가 필요하면 의견으로 문의하십시오!

+3

당신에게 쓰기를 위해 파일을 연 다음 그 파일을 읽으려고했습니다. – martineau

답변

1

당신은 "wb"로 쓰기 위해 .read()

당신은 그것을 열었다을 사용하기 위해 읽기 위해 파일을 열 필요가있다.

사용 "rb""wb"는 쓰기, 읽기 및 "ab"

'+'"ab+" 등을 첨가 추가 할 수는 다른 모드에 대한 참조가 있습니다

를 작성/simulaneous 읽기 및 추가 가능 here

예 :

with open("filepath/file.ext", "ab+") as fo: 
    old = fo.read() # this auto closes the file after reading, which is a good practice 
    fo.write("something") # to the end of the file 
+0

이것은 매력처럼 작동합니다, 감사합니다! –

3

당신은 open(filename, "ab+") 원하는 :

추구 모드는 당신도 기존의 내용을 읽을 필요가 없습니다 "추가"를 또한

The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing.

(0) 등을 수행 할 수 있습니다 그냥 일반 쓰기 :

[email protected] ~/Work/playground $ cat yadda.txt 
foo 
bar 
[email protected] ~/Work/playground $ python 
Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> f = open("yadda.txt", "a+") 
>>> f.write("newline here\n") 
>>> f.close() 
>>> 
[email protected] ~/Work/playground $ cat yadda.txt 
foo 
bar 
newline here 
[email protected] ~/Work/playground $ 
+0

작동하지만 끝 부분에 추가하지 않습니까? http : //pastebin.com/mnjbpy0w –

+0

'추가'모드로 읽기/연결/검색 (0) 할 필요가 없습니다. 에. –

관련 문제