2012-06-24 4 views
13

가 나는 ERR "[errno를 0] 오류 IO 오류를"있어? 이 두 사례 아래의 확인은 다음과 같습니다파이썬 파일 작업

from sys import argv 
file = open("test.txt", "a+") 
print file.tell() # not at the EOF place, why? 
# print file.read() # 1 
file.write("Some stuff will be written to this file.") # 2 
# there r some errs when both 1 & 2 
print file.tell() 
file.close() 

과 :

print file.tell() # not at the EOF place, why? 

파일의 크기를 인쇄하지 않는 이유를 여전히

from sys import argv 
file = open("test.txt", "a+") 
print file.tell() # not at the EOF place, why? 
print file.read() # 1 
# file.write("Some stuff will be written to this file.") # 2 
# there r some errs when both 1 & 2 
print file.tell() 
file.close() 

, "A +"추가] 모드입니다 ? 파일 포인터가 EOF를 가리켜 야합니까?

저는 Windows 7과 Python 2.7을 사용하고 있습니다.

+0

에서 open을 사용하는 것입니다? 문제는 추가 모드에서 열린 파일을 읽으려고하는 것 같습니다. – Dhara

+0

또한 text.txt가 있는지 확인하십시오. – Dhara

+0

코드가 제대로 작동합니다. 'tell'은 파일을 연 직후'0'을 리턴합니다. 물론, 다른 것을 기대해야하는 이유는 무엇입니까? –

답변

10

파이썬은 stdio의 fopen 함수를 사용하고이 모드를 인수로 전달합니다. @Lev는 코드가 리눅스에서 잘 작동한다고 말하기 때문에 당신이 윈도우를 사용한다고 가정하고있다.

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

그래서,이 솔루션은 file.write() 호출 이전 file.seek()을 추가하는 것입니다 : 다음은 윈도우의 fopen 문서에서입니다

,이 문제를 해결하는 실마리가 될 수 있습니다. 파일 끝에 추가하려면 file.seek(0, 2)을 사용하십시오.

To change the file object’s position, use f.seek(offset, from_what). The position is computed from adding offset to a reference point; the reference point is selected by the from_what argument. A from_what value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. from_what can be omitted and defaults to 0, using the beginning of the file as the reference point.

[참조 : http://docs.python.org/tutorial/inputoutput.html] 그의 대답에 의견과 @Burkhan에 @lvc에서 언급 한 바와 같이

, 사용할 수있는이 새로운 다음과 같이 참고로

는 file.seek 작동 io module에서 열린 함수입니다. 그러나, 나는 쓰기 기능이 경우 동일 작동하지 않는 것을 지적 할 - 당신이 [간단히 귀하의 경우 문자열에 u 접두사] 입력으로 유니 코드 문자열을 제공해야합니다

from io import open 
fil = open('text.txt', 'a+') 
fil.write('abc') # This fails 
fil.write(u'abc') # This works 

을 마지막으로, '파일'이라는 이름을 변수 이름으로 사용하지 마십시오. 내장형을 참조하기 때문에 자동으로 덮어 쓰여 오류가 발생하기 쉽습니다.

+0

'a +'는 읽을 수있다. –

+0

@LevLevitsky, 나는 설명서에서 그걸 확신 할 수는 없지만, 코드가 작동한다는 것. – Dhara

+0

또한 존재하지 않는 파일도 오류없이 열립니다. –

6

이 솔루션을 사용하면 오류가 발생하는 곳 io

D:\>python 
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on 
win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> f = open('file.txt','a+') 
>>> f.tell() 
0L 
>>> f.close() 
>>> from io import open 
>>> f = open('file.txt','a+') 
>>> f.tell() 
22L